PHP Sessions

Sessions are used to store information which can be used through-out the application for the entire time the user is logged in or running the application. Each time a user visits your website, you can create a session for that user to store information pertaining to that user.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session

Now lets learn how we create a session in PHP.

Before you can store any information in session variables, you must first start up the session using the session_start() function. See below.

Note: The session_start() function must appear BEFORE the <html> tag:

<?php
session_start();
?>

<html>
<body>

</body>
</html>

Storing information in a session

To store information is a session variable, you must use the predefined session variable $_SESSION.

Now, as an example, lets store user’s name and their age in a session. To do so you would do the following.

<?php
session_start();

$_SESSION["username"] = "qpt";
$_SESSION["age"] = "25";

?>

Retrieving stored session information

Retrieving stored session information is really easy. You can access the stored session information on any page without doing anything extra.

<?php
session_start();

echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["age"];

?>

The output of the code above could be something like this:

qpt
21

Destroying/deleting session information

Remember sessions are destroyed automatically after user leaves your website or closes the browser, but if you wish to clear a session variable yourself, you can simple use the unset() function to clean the session variable.

<?php
session_start();

unset($_SESSION["username"]);

unset($_SESSION["age"]);

?>

To completely destroy all session variables in one go, you can use the session_destroy() function.

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

Posted in Php