When you have more than one page in your PHP-based website and want to keep track of or personalize user activities, or when your application grows to more than just an information board, then it is time to maintain state in the site. The main purpose of maintaining state in PHP applications is to keep track of users and their activities. It can also be used to limit a user's ability to access certain components of a website.
Without maintaining state, an e-commerce site would not be able to support shopping on the Internet, because the shopping cart needs to "remember" the products you selected to buy and it needs to maintain state for that.
So, why can't you maintain state with HTTP? The main reason is because HTTP is a stateless protocol, meaning that it has no built-in way of maintaining state between transactions. For example, when a user requests one page followed by another, HTTP does not provide a way for us to tell which user made the second request.
In this article we will look at what maintaining state in PHP applications entails. Specifically, PHP offers two methods for tracking data. The first is cookies and the second is called sessions. We will be looking at these methods in detail.

Using Cookies in PHP to Maintain State

What are "cookies"? Cookies provide a way for a server to store information about a user on the user's machine. The purpose for this is mainly for the server to remember who you are every time you visit a particular site. Think of it as a name tag or identifier that the server assigns to you.
On a more technical level, cookies are basically text files stored by websites on a computer that accesses websites. Each cookie can contain around 4,000 characters, and up to 20 cookies can be stored for each website. The client can store a maximum of 300 cookies. As you might expect, the text in cookies are stored in plain text, so if you are going to store sensitive data, you will have to encrypt it to be more secure.
To create a cookie in PHP, the setcookie() function must be used at the top of your PHP script. No white spaces or any kind of text should precede the calling of the function. In the example below, we use a form to collect the name and age of a user and then store that information in a cookie:
<?php
   if(isset($_POST['submit'])){
   
   $err = "";
   echo "dghsdgh";
   //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 ){
setcookie('User', $_POST['txtname']);
setcookie('Age',$_POST['txtage']);
echo "Cookies 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>Handling Cookies in PHP</title>
<style type="text/css">
<!--
.style1 {font-size: 14px}
-->
</style>
</head>

<body>
<form id="form1" name="form1" method="post" action="setcookie.php">
<table width="100%" border="1">
  <tr>
    <td colspan="2"><h1>Set Cookie Form </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>
To view the cookie data, we can simply open up the cookie file on the system using any text editor or we simply write a routine similar to how you would retrieve a form value. For example, if you've set a cookie value like this:
setcookie('Username','MyName')
Then you would retrieve it like this:
If(isset($_COOKIE['Username'])){
echo $_COOKIE('Username');
}

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.