The prime reason why server-side scripting languages are popular is that they support sessions. A session can be used to remember user details across pages. Suppose you sign in into your Facebook account and visit the settings page. To do this you don't have to sign in again. Facebook remembers that you have already signed in using a session cookie. This is possible using a feature called sessions. In this article I will teach you about handling sessions in PHP.
The first thing that is to be learned in Session handling is how to start a session. A session is usually started when a user logs in to a website. The PHP function session_start()
is used to start a session in PHP. The same function can be used to continue a session (if it already exists). Usually, after starting a session, a few session variables are set (like id). This is done using the $_SESSION[]
superglobal variable. $_SESSION[]
is an associative array. To set a session variable, just add a key-value pair to the array. So when the user visits another page we can check whether or not he/she is logged in by checking whether or not a particular session variable is set.
// starts a new session
session_start();
// set a session variable called id
$_SESSION["id"] = $_POST["id"];
This can be the code in a login page. Suppose that, after login, a user visits another page in the same website. We obviously don't want him to login again. We need to first check if the user is already logged in. If yes, we let him view the page. Else, we redirect him to a login page (possibly containing a login form).
// continue an existing session if it exists
session_start();
// check if the user is logged in
if (!isset($_SESSION["id"]))
header("Location: login.html"); // redirect
// the content of the page follows...
So, that was starting a session and checking whether a session is active. Now, let's see how one can end a session. The most common situation in which we would want to end a session is when the user logs out. To end a session, just use the session_destroy()
function.
session_start();
// unset all session variables
$_SESSION = array();
if (isset($_SESSION["id"])) // if the user is logged in
session_destroy();
// ..
You can learn more about the above mentioned functions at php.net.