i

PHP Tutorial

PHP Session Handling

Session is a way to store the information to navigate to multiple pages and the variables last till a user closes the browser. For example, When you login to any social account or your email you use it by reading mails, sending email, changing personal details etc. When you log out your account after you use it, the time between you login and logout is a session.

Session variable works on all the pages linked to your social account. Example, your name gets displayed on the corner in your email even if you change the page, the name displays on every webpage. When you log out, the name will also not be shown.

1 Starting a Session

In PHP, you can start a session using session_start() function and the variables are set using $_SESSION global variable. You need to use session_start() function on all the pages where you want to start the session.

For example;

session_start();

$_SESSION[“username”]= “Ben”;

echo “Session”. $_SESSION[“username”]. “is started”;

?>

2 PHP Session Variable Values

You can set session variable values as we have seen in the above example like an array. We have started the session and set the value in one webpage, but we can retrieve the value of the current session in another webpage also. For example, if we create another php file and write the below code, we can access the value set on the above page.

session_start();

?>

echo “ The username for current session is” . $_SESSION[“username”];

?>

Output of the above php code will be: The username for current session is: Ben

3 Modify a Session Variable

You can modify or update a session variable simply by overwriting it. You can change the value of the $_SESSION variable as below:

session_start();

?.

$SESSION [“username”] = “Paul”;

echo “ The updated username is :”.$_SESSION[“username”];

?>

The output of above php code will be: The updated username is: Paul

4 Destroy a Session

You can destroy a php session using session_unset() and session_destroy() functions. session_unset() function removes or delete all the session variables and session_destroy() function destroys the session.

For example:

session_start();

?>

session_unset();

session_destroy();

?>