15 - Working with session and cookies in PHP

Session Introduction

Session is a time period during which a person uses a machine for web browsing and then quits. In PHP a session must takes care of following two things:

  • Session tracking information
  • Storing information associated with a session.

HTTP (hyper text transfer protocol) is a stateless protocol. It means that this protocol does not maintain state between two transactions. HTTP does not provide a way for identification that two requests came from one user.

In PHP sessions can be identified using session ID. This session ID can be visible at client side. Session ID can be either stored on user’s computer in a cookie or can be passed along with URLs. Sessions use a cookie PHPSESSID to store session ID. When we start a session PHP check for the presence of this cookie, if it does not exists it will be set and provide a random string in this cookie, each client will get unique string.

If we want to use a session in a page we call session_start() method at the beginning of our script. This method should be called before any output is sent. If we want to use session in our all pages, we should set the configuration directive in php.ini file as:

    session.auto_start = on

    Session Information:

    Session data is stored in $_SESSION auto global array.

Example:

session_start();
$_SESSION['count']=$_SESSION['count']+1;
echo 'welcome to this page this is your' . $_SESSION[‘count’] . 'visit';

When user visit first time this page, PHPSESSID cookie will be created and $_SESSION[‘count’] array will be empty, so $_SESSION[‘count’]+1 set the value 1. The output of above code will be:

    Welcome to this page this is your 1 visit

PHP session need more space as compare to cookies. Session data is stored on web server in a temporary directory. If we are using Unix OS on web server we need not to do anything to store session data, In UNIX /tmp directory is used by default for this purpose.

Normally session uses cookies to store data, but if cookies are disabled on browser setting then PHP sessions can also work without cookies. In this scenario PHP session data can be stored as:

We can use some hidden input tags in HTML forms with the name PHPSESSID just after the <form> tag. Whatever the value we assign in that input tag will be assigned to session ID.

<form>
   <input type="hidden" name="PHPSESSID" value="9002345">
</form>

When we use links in HTML code, PHP automatically modify these links and use PHPSESSID in form of GET parameter in URL query string.

It is not mandatory that we should use PHPSESSID name to hold PHP session value. We can also change it in php.ini file.

Session configuration

By default session can be accessed for every 24 minutes. This default setting can be configured also. If we have to deal with critical transactions online then for the reduced chances of unauthorized access we can reduce it also by using session.gc_maxlifetime directive. We can change this directive in server configuration or we can also call ini_set() function for it.

Example:

<?php
  int_set('session.gc_maxlifetime',180);     // 180 seconds=3 minutes
   session_start();
?>

Session Handler:

To handle the session in PHP SessionHandler class can be used. There are various methods available in this class (open, close, read, write, destroy, gc and create_sid). This class contains all the files defined by session.save_handler directive.

SessionHandler implements SessionHandlerInterface
{
//class methods
public bool close();                                                              //close the session
public string create_sid();                                                   //return a new session id
public bool destroy(string $session_id);                            //destroy a session
public bool gc( int $maxlifetime) ;                                     //clean up old session data
public bool open(string $save_path,string $session_id);  // open a new session
public string read(string $session_id);                              //read information of current session
public bool write(string $session_id,string $sessiondata); //write the session data
}

Session and security features in PHP

While using PHP, developer should maintain some security measures by applying settings for session management. Such as

   session.cookie_secure=on

   session.cookie_httponly=0n

   session.use_cookie=on

   session.gc_maxlifetime=[time in seconds]

   session.use_strict_mode=on

   session.cookie_lifetime=0

Session functions

Some session functions are available those are responsible to handle various session related activities: such as

 

Figure - Session Functions

                                                Figure - Session Functions

Cookie introduction

Cookie is a small piece of information that can be stored on a client side machine by PHP script. We can set a cookie on a user’s machine by sending an HTTP header containing data in key value pair format.

Usually cookie is used to store single information about any client in name-value pair, but if the requirement is to store more information about a user like contents of shopping cart, multiple cookies should be used that is very tedious task. I this case we should use session capability of PHP to store multiple information.

For eg:

    Set-Cookie: NAME=VALUE; [expires=DATE;] [path=PATH;] [domain=DOMAIN_NAME;] [secure]

Here cookie will be created called NAME with the value VALUE. The expires field sets a date beyond which the cookie is no longer relevant. The path and domain can be used to specify the URL. The secure keyword means that the cookie will not be sent over a plain HTTP connection.  Whenever a browser connects a URL, it firstly search the cookie stored on local machine

 

Working with Cookies:

   To set a cookie we have to use setcookie() function.

Syntax of setcookie() function:

   setcookie ( name, value, expire, path, domain);

How to access cookie information

     Cookies can be retrieved using $_COOKIE global variable like:

      echo $_COOKIE[“user”];

Example:

<?php
  setcookie('username','James Smith');
?>
<html>
 <head>
   <title> Cookie Page</title>
 </head>
 <body>
    This page will create a cookie named username and store value James smith in it for further identification.
 </body>
</html>

Like us on Facebook