PHP session is used to store information on the server. The data will be available to all pages in one application.



A session creates a file in a temporary directory on the server where registered session variables and their values are stored.

Starting a PHP Session

Before use session variables, you must first start the session using the session_start() function.

The Function session_start() should be in starting, and you can't send anything to the browser before it.

Example:

<?php
session_start();
?>

<html>
<body>

</body>
</html> 

When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP session_id() function or predefined constant PHPSESSID.

Storing a Session Variable

$_SESSION[] is an associative array, which is used to store information is a session. These variables can be accessed during the lifetime of a session.

Example:

<?php
session_start(); 

// store session data
$_SESSION["username"] = "nikita";
$_SESSION["email"] = "[email protected]";

//retrieve session data
echo $_SESSION["username"];
echo "<br>";
echo $_SESSION["email"];
?> 

Destroying a Session

A complete PHP session can be terminated by using session_destroy() function, which does not require any arguments.

Example:

<?php
session_start();

session_destroy();
?> 

If you wish to delete a single session variable, then you can use unset() function.

Example:

<?php
session_start();

if(isset($_SESSION[username]))
unset($_SESSION[username]);
?> 


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram