Session in PHP:

A PHP Session is an alternative way to save data in a variable and that variable is accessible across the all pages in the web site.

Means you have to create a session variable in a web page and you can use that variable in any another web page of your web site.

 Why use Session?

When a user work with an online application he opens the application, do some changes over it and than close that application. The computer knows who the user is and when he starts the application and when user ends it. But the server doesn’t know about user because the information is not saving on the user’s computer like Cookies.

So the session variable solves this problem because we save the session in a variable and use that variable across our web site.

 Starting a PHP Session:

To start a PHP Session you have to use “session_start()” function in PHP. This function checks that the session is start in PHP page or not if not than it will start the session and one thing you have to know that always start a session in the beginning of the page.


 Creating a Session Variable in PHP:

To create a session variable first you have to start a session by “session_start()” function and than we create a session variable with “$_SESSION” . $_SESSION is a global variable means you can use this variable in any web page of your site.


In following example we are printing session variable with echo statement

You can also define session variable as an array


In following example we are printing session variable with print_r() function .

 Destroy a PHP Session:

To destroy a session in PHP you can use two functions one is “session_unset()” and second one is “session_destroy()” .

The main difference between session_unset() and session_destroy is session_unset() function delete the value of session variable and session_destroy() function delete the value as well as the session variable also.



Leave a Reply

Your email address will not be published. Required fields are marked *