Back-End Development PHP basics

Creating php sessions

Creating php sessions -basics

A brief about PHP sessions

When you start an application, work on it and then close it, it is a session. Your computer knows who you are. It knows when you start an application and when you close it. But the problem with internet is, it cannot recognize users.HTTP protocol is a stateless protocol. It does not remember what happened in past

The question can be why do we want internet to remember users?
One example can be, user accessing an shopping site, where when the user moves among pages, information is required to know the user to customize preferences.

The two possible ways to store this information of user are COOKIES and SESSIONS.
Cookies are different from sessions because cookies are stored as something permanent for some time. In contrast to that, whatever we store in sessions only last until the user doesn’t close the browser window.


A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e7887.
  • A cookie named PHPSESSID is stored on user’s computer to be used as session identification string.
  • A file is automatically created in the temporary directory with the name prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e7887.

When PHP wants to retrieve the values of the session variables, the unique session identifier can be found from the cookie PHPSESSID. Then PHP can look for the file bearing that name in the temporary directory.And the validation can be done on matching both values.

Creating php sessions

Start a PHP session

A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
This is illustrated:

$_SESSION['name']="Scanfcode"; sets the session with name =name and value=Scanfcode.

Getting session values

The output will be:
Hello,my name is:Scanfcode.
My job is:blog

Destroying a session

To destroy all sessions use: session_destroy();

To remove a specific session use:

This function will remove only session work.