New way to learn PHP

PHP 5 Session

What is Session?

Sessions are used in PHP to provide a method to track a user throughout a website and pass data between pages about that user during their time on the site. A unique ID is assigned to the user and the data is stored on the server itself, rather than on the user's computer such as with cookies. The most common form of session usage is for commerce sites and the ability to have a shopping cart, user login and customized interfaces, and navigation history.

  • Session are great for storing data about the visitor

How Session works?

PHP allows you to create a session and store session variables. After you create a session, the session variables are available for your use on any other Web page

  • PHP assigns a random session ID number
  • PHP stores the variables that you want saved for the session in a file on the server
  • PHP passes the session ID number to every page.
  • PHP gets the variables from the session file for each new session page.

Difference between session and cookies?

  • The main difference between cookies and session is that a cookies is store on the client machine while a session data store on the server
  • Session is more secure than cookies

PHP session function

There are three function in session are following below

  1. Session_start()
  2. Session_id()
  3. Session_destroy()

Session_start(): create a session or resume the current one based on the current session id.

Session_destroy() :At some point in an application, session may need to be destroyed. Like time of logs out the application then call the session_destroy function.

Session_id(): PHP provide a Session_id() function that return the session identifier for the initialize session, started using Session_start().

Creating Session using PHP

Sessions in PHP are very easy to create. To start a PHP session in your script, simply call the session_ start () function. You should open a session at the beginning of each Web page.


session_start() ;

Reading and Writing Session Data

Working with session data in PHP is also simple. You store all your session data $_SESSION super global array. That means each session variable is one element of array.

Syntax of writing session variable

$_SESSION ['var-name'] = < value > ;

Syntax of Reading session variable

echo( $_SESSION[ "var-name" ] );

Before adding session variable, session_start () must be include in start of page

Example of start session


$a=$_SESSION ['no'] =$_SESSION ['no']+1;
echo "you are visted ".$a."times";

  • Example

Example of session id


$id = session_id();
echo "current session id :".$id;

  • Example

Destroying a Session

You can use session_destroy () function to end a session.


Example of desrtoying session


$a=$_SESSION ['no'] =$_SESSION ['no']+1;
echo "you are visted ".$a."times";

  • Example


Knowledge itself is a power.