ankitweblogic logo
W e b t u t o r i a l s

Define PHP

PHP Installation

PHP INI File

PHP Case Sensitivity

PHP Variable

PHP Echo & Print

PHP Operators

PHP Receiving Input

PHP Decision Making

PHP Loops

PHP Jumping Statement

PHP Image Gallery

PHP Arrays

PHP Date Functions

PHP String Functions

PHP Math Functions

PHP Functions

PHP Variable Scope

PHP Constant Variable

PHP Superglobals

PHP Form Validation

PHP Include Statement

PHP Filter

PHP File Handling

PHP File Upload

PHP Cookies

PHP Session

PHP Send Emails

PHP Captcha

PHP-MySQL Connectivity

PHP MySQL Select

PHP MySQL Insert

PHP MySQL Delete

PHP MySQL Update

PHP Session

A session is a way to store user's information (in variables) to be used across multiple pages (e.g. id, name, age, etc). Unlike a cookie, the session information is not stored on the users computer. Normally, session variables are expire when the user logout from the account.

So; Session variables hold information about one single user, and are available to all pages in entire application. To declare a session variable use the session_start() function. Session variables are set with the PHP global variable: $_SESSION.

Example : Create a page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["id"] = "Ritika@gmail.com";
$_SESSION["age"] = "25";
echo "Session variables are set.";
?>

</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.

Retrive PHP Session Variable Values

Now, we create another page called "demo_session2.php". From this page, we will access the session information that we have set on the first page ("demo_session1.php").

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we created at the beginning of the page (session_start()).
Note: that all session variable values are stored in the global $_SESSION variable:

Example: Retrive Session Variable Values

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Email Id is " . $_SESSION["id"] . "
"; echo "Age " . $_SESSION["age"]; ?> </body> </html>
Example : Another way to show all the session variable values for a user session is:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session

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

Example : Destroy a PHP Session

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset(); 

// destroy the session 
session_destroy(); 
?>

</body>
</html>