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.
<?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.
<?php session_start(); // store session data $_SESSION["username"] = "nikita"; $_SESSION["email"] = "firstname.lastname@example.org"; //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.
<?php session_start(); session_destroy(); ?>
If you wish to delete a single session variable, then you can use unset() function.
<?php session_start(); if(isset($_SESSION[username])) unset($_SESSION[username]); ?>