×
☰ See All Chapters

PHP Sessions

Unlike Session Management with Cookies, client can send many requests to the application and the application has to remember all the requests coming from the client. Registration applications have to remember data from different pages like personal profile, education details, professional details etc.… Before client presses confirm/register button. There will also be multiple clients accessing the same application with multiple requests. When we use Session variable (when we create $_SESSION variable) to store client specific data, automatically one value called JSESSIONID generated by the server for every client, is exchanged between the client and server to keep track of session. By default JSESSIONID is exchanged between the client and server using cookies. Once session variable is created, JSESSIONID is generated by the server and is added to cookie, since cookie is exchanged between client and server automatically we need not to keep track of session.

Start a PHP Session

A session is started with the session_start() function.

Store a session variable

Session variables are set with the PHP global variable: $_SESSION

Syntax: $_SESSION["sessionVariableName"] = "valueOfSessionVarible";

Get PHP Session Variable Values

All session variable values are stored in the global $_SESSION variable, we can retrieve the value of session variable using name from the $_SESSION global variable;

Syntax: $session_value = $_SESSION["sessionVariableName"];

Modify a PHP Session Variable

To change a session variable, just overwrite it by setting again session variable with same name.

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy().

PHP Sessions example

<?php

// Start the session

session_start();

?>

<!DOCTYPE html>

<html>

<body>

 

<?php

// Set session variables

$_SESSION["favcolor"] = "green";

$_SESSION["favanimal"] = "cat";

echo "Session variables are set.<br>";

?>

 

</body>

</html>

 

<?php

// Echo session variables that were set on previous page

echo "Favorite color is " . $_SESSION["favcolor"] . "<br>";

echo "Favorite animal is " . $_SESSION["favanimal"] . "<br>";

?>

 

<?php

// remove all session variables

session_unset();

 

// destroy the session

session_destroy();

?>

 


All Chapters
Author