Using Sessions in PHP to Maintain State
The second method available in PHP is sessions. A session, like cookies, provides a way for you to keep track of users. The main difference between the two is that cookies store their data on the client machine, while sessions store their data on the server machine. The biggest advantage that sessions have over cookies is that they do not require the user to have them enabled on their browsers. When you start a session, PHP creates a session ID, which acts as a reference to that particular session. PHP pages then access this information as needed.
To create a session in PHP, you must use the
session_start()
function. This function will send a cookie to the Web browser. Like set_cookie()
, no white spaces or code or anything else should precede this function. Once a session is started, PHP sends a cookie to the browser with a name of PHPSESSID
and a 22 character string. You can then assign values to the $_SESSION
array like so:
$_SEESION['age'] = 5
Every time you assign a value to a session variable, PHP writes that data to a temporary file on the server.
To demonstrate the use of sessions, let’s modify the script that we used previously to assign cookie values:
<?php
session_start();
$err ="";
if(isset($_POST['submit'])){
//check if the form values are not empty
if(empty($_POST['txtname'])){
$err.= "Please enter a name.";
}
if(empty($_POST['txtage'])){
$err.= "Please enter a age.";
}
if(strlen($err) < 1 ){
$_SESSION['uname'] = $_POST['txtname'];
$_SESSION['age'] = $_POST['txtage'];
echo "Session set";
}else{
echo "The following errors occurred: ".$err;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Maintaining State in PHP</title>
<style type="text/css">
<!--
.style1 {font-size: 14px}
-->
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="createsession.php">
<table width="100%" border="1">
<tr>
<td colspan="2"><h1> Create Session </h1></td>
</tr>
<tr>
<td width="19%">Name</td>
<td width="81%"><label>
<input name="txtname" type="text" id="txtname" />
</label></td>
</tr>
<tr>
<td>Age</td>
<td><label>
<input name="txtage" type="text" id="txtage" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input name="submit" type="submit" id="submit" value="submit" />
</label></td>
</tr>
</table>
</form>
</body>
</html>
This gives us:
Click here for larger image
Figure 1. Result of Assigning Cookie Values
In the script above, we set the username and age and assign those values to session array:
$_SESSION['uname'] = $_POST['txtname'];
$_SESSION['age'] = $_POST['txtage'];
To read those values from the server, we simply print them out like so:
<?php
session_start();
$nameAge="";
if(isset($_SESSION['uname'])){
$nameAge.= "Username is: <strong>".$_SESSION['uname']."</strong> ";
}
if(isset($_SESSION['age'])){
$nameAge.= "User Age: <strong>".$_SESSION['age']."</strong>";
}
echo $nameAge;
?>
The code produces the following result:
Click here for larger image
Figure 2. Printout of Values from the Server
Deleting Session Variables in PHP
Now to avoid cluttering up the server with all the session variables that we created, PHP provides ways of deleting your session variables:
<?php
session_start();
//delete session variables
unset($_SESSION);
//delete session data
session_destroy();
echo "Session data removed";
?>
The code above first calls the
session_start()
function to open up any session that is currently active and then uses the unset()
function to delete session variables. The final function it then calls is the session_destroy()
function; its purpose is to destroy any session data that is still remaining.Conclusion
Cookies and sessions are a very effective way to keep track of any activity on your website. Arguably, sessions are better because they provide the best and safest method of tracking activity in your applications.