Session Handling in php

Session is a very powerful feature that is offered by php. Now question is what is session?

Session

Session is a logical object that offers a complete functional transaction to the user. For example like in gmail, when u signin through ur google account then session is created and when u logout session is destroyed. Its due to session when u go from one page to another page it never ask you to submit ur gmail id again, so session offer users complete functional transaction.

Session store all the information of the user in its session variables and then make this avilaible to all pages in the whole application.

Where sessions are used in the Web Site?

Sessions are normally used when user successfully login through its account, as i give u gmail example earlier. Session is a very powerful thing without session you cannot imagine to built a website that allows user to register first and then allowing signin process and then want to know what user will do after signing in.

For example there are lot of websites who offers online shopping, shopping cart cannot be made without sessions.

How to create sessions in php?


  1. First of all create the session object like this session_start();

  2. Create the session variable and store value in it like $_SESSION['username']="Adeel Fakhar";
  3. Now just call this username in all pages but one thing make sure always declare session_start(); at top, there should be no thing before it, else u may get errors.

How to unset and destroy session?

Normally we unset session and destroy session at logout page. unset() will clear all session variables and session_destroy() just destroy all the session.

Example:-

In logout page just write this code

session_start();

unset($_SESSION['username']);

session_destroy();

View the session demonstration in the images below








0 comments: