Basic PHP Sessions

Posted under » PHP on 25 July 2013

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Before you can store user information in your PHP session, you must first start up the session. This will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

<¿php 
session_start(); 
?>

When you do that, a session id is created by the PHP server. Your browser can tell what is that session ID by using firebug. So it is best not to use it for security purposes. Other than that if another user use the same browser, then they will share the same session ID.

You can use show what it is by

echo "<p>session id : ".session_id();

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<¿php 
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<¿php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html> 

To see all your session variables.

print_r($_SESSION);

In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

<¿php 
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?> 

If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable:

<¿php 
session_start();
//individual
if(isset($_SESSION['views']))
  unset($_SESSION['views']);
//general
session_unset(); 
//   or complete destroy
session_destroy(); 
 ?> 


 

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css