Session Handling in PHP using $_SESSION

Session Hanlding In PHP: setsession();

What is a PHP session?

You can assume the session in PHP or in other scripting language for that matter, as something which keeps track of a specific request. The normal without any session request is processed by a web server as below.

  • The browser makes a request.
  • The web server accepts the request and processes it. Finally it sends back some response to the requester (the browser, mostly) and forgets about the request.
  • If the same browser again makes some other requests, the web server does not know that it has just served this specific browser. It treats the request as a new request.

A typical transaction using the session object will be something like this.

  • The browser makes a request to the web server.
  • This time the web server creates a web session or simply session object on its own machine(web server's) and assign some unique name or id to it. This unique Id is often called as the session id.
  • The web server processes the request and sends the session id as header while sending response back to the browser.
  • When the browser makes request to the web server, it sends the session id also with the request. The web server check for availability of the session corresponding to the id. If it finds the session live, It knows that this is not the first time the browser has requestd some services!

Why do we use sessions?

We use sessions to generally keep the track of a successfully logged in user. We store some user-specific information in the session object. This information might be the user id of a successfully logged in user, or the shopping contents on a cart based website etc.

Advantage of using SESSION object.

As compared to cookies, the advantage of using a session is that all the information are stored on the server machine only hence it is more secure.



Disadvatnage of using session.

The performance might degrade if lots of session objects co-exist on the server machine. This will result in delayed response and might annoy the end users. However using good dedicated hosting solutions may help you. With dedicted hosting the server resources are not shared by anyone else. All the CPU time is available to your own application only, Which results in better performance.

After so much gyan let us learn PHP specific Sessions. In the next section we will learn how to create a PHP session.


Create PHP Session Object: session_start();

You need to start a session in PHP before you can add information to this object. The function session_start() creates a new session object. This function does not take any argument. If a session is already active, this function is ignored.

To save a value to your just started session variable, you should use the inbuilt PHP array $_SESSION[ ]; This array is again used to retrieve values also. The following script starts a new session if one not already active and saves the user name as "john".


session_start();
$_SESSION["user_name"] = "john";

To retrieve the value of user name, just use the $_SESSION["user_name"]. Simple! Isn't it?


Destroy A Session: session_destroy()

Unset a session value
To unset a session value, use the same old unset() function. The following code destroys the variable. After unsetting this variable the isset() function returns false for the variable.

unset($_SESSION["user_name"]);

Destroy a session completely

If you want to destroy a session itself. You can destroy a session completely in PHP using the session_destroy() function. The example below destroys the session completely.

session_destroy();


Working example on PHP Sessions
The script below creates a new session. It then shows the no of views till the no. of views reaches 5. Once the page has been viewed for 3 time, the script destroys the session and starts a new session.

<?php
session_start();
if(isset($_SESSION["user_visit"]))
{$_SESSION["user_visit"] = $_SESSION["user_visit"] + 1;}
else
{
$_SESSION["user_visit"]=1;
}
if($_SESSION["user_visit"]==5)
session_destroy();
?>
<html>
<head>
<title>Session Visits</title>
</head>
<body>
This is your <?php echo $_SESSION["user_visit"]?> visit!
</body>

</html>


More example on PHP Sessions
OK, now The example below is a little more elaborate and it shows how a typical session handling can be done. If you learn this, you will be able to create a typical login application easily.

<?php session_start();
if(isset($_SESSION["user_name"]))
if($_GET["destroy"]=="yes")
{
unset($_SESSION["user_name"]);
session_destroy();
}

if(!isset($_SESSION["user_name"]) &&
$_GET["user"]!="")
$_SESSION["user_name"] = $_GET["user"];

?>
<html>
<head>
<title>Session Example</title>
</head>
<body>
Welcome <?php echo $_SESSION["user_name"]; ?>
<form action="#">
Input your name here: <input type=text name=user>
<input type=submit value=Submit>
</form>

<form action="#">
<input type=hidden value=yes name=destroy>
<input type=submit value="Destroy Previous Session">
</form>

<p>
The first time you input your name,
It will be stored as a session object.
So every time you pression submit button
or refresh the page, you will se the name
you entered for the first time!.
</p>
</body>

</html>

Notice that the session has been started before any HTML output has been sent. Just like setting a cookie, a session must always be started before committing any output.