How to Use PHP Sessions to Store Data .

Download Tutorials, Source code, Projects and Take free project guidance in

Welcome to PHP programming,
In this tutorial we will explain How to Use PHP Sessions to Store Data
In PHP, session variable is used to store information about, or change settings for a user

PHP Session Variables

Session variables hold information about one single user, and are available to all pages in one

The web server does not know who is the user and what the user does because HTTP address does not
maintain state.

A PHP session solves this problem by allowing the user to store user information on the server
for later use(i.e., username, etc.).

However, session information is temporary and will be deleted after the user has left the website.

If you need a permanent storage you may need to store the data in database.

Session 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 a propagated in the url.

Starting a PHP sessiom

Before storing user information in PHP session, we must first start up the session.


The session_start() function must appear before html tag.

The code above will register the user’s session with the server, allows to start saving user
information, and assign a UID for that user’s session.

Storing a Session variable

The correct way of storing and retrieving a session variable is to use the PHP $_SESSION

Let us write a simple PHP code to store and retrieve session.

Save it in our server i.e., xampp/htdocs

Run the code using the url http://localhost/phpstore.php

Destroying a Session

To delete session data, unset() or the session_destroy() function is used.

The unset() function is used to free the specified session variable.


To completely destroy the session the session_destroy() function is used.


session_destroy() will reset session and all the stored session data will be lost.

Let us write a PHP code using sessions

Save it in our server i.e., xampp/htdocs

Run the code using the url http://localhost/phpsession.php

Let us write a code to destroy the session that we created

Save it in our server i.e., xampp/htdocs

Run the code using the url http://localhost/phpdestroy.php

This is how session works with PHP script.

Thank You…….

For source code kindly refer