PHP session tutorial - Check sessions


Home - Tutorials - Sessions

In this tutorial I will show you how to work with sessions in PHP. You will learn how to transfer information between pages.

Tutorial info:


Name:PHP session tutorial
Total steps:5
Category:Sessions
Level:Beginner

Bookmark PHP session tutorial



Bookmark and Share

Step 4 - Check sessions


PHP session tutorial


In the previous example I used 2 different files to demonstarte basic session behaviour. However by checking session status we can create a much better code. To check whether a session variable exists or not you can use the isset() function.

So in the next code we will first check if the username is set or not. If it is not set yet then we will set it else we will display it. As result if call the code twice you will get different output. The code is the following:

Code:
  1. if (isset($_SESSION['username'])){
  2. echo "User : ".$_SESSION['username'];
  3. } else {
  4. echo "Set the username";
  5. $_SESSION['username'] = 'John';
  6. }
  7.  
However if you have executed the first example as well then you will never get the message "Set the username" as you have done it in your very first call. If you wait until the session is expired and execute the code again you will get the set message.

In the next step you will learn how to clean session data.





Previous Step of PHP session tutorialNext Step of PHP session tutorial


Tags: php sessions, php, session, session handling



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0103