PHP Sessions

In PHP, session is a method which can be used to store information which can be accessed on any page whenever needed on the website.

What is a session in PHP

Basically, sessions are used to identify the use identity and the server sends the same information related to that user only which is stored in session variable. For example, when you logged into your gmail or yahoomail account then how the server knows what information to be sent to the user who is currently logging into the account. This makes possible because of sessions. So whenever a user logged into their account, browser immediately sends a request with the session ID and server displays all the information related to that particular user only.

How the session work in PHP

  1. Whenever a session start, PHP creates generate a unique identifier of 32 bit hexadecimal numbers which could be any random number.
  2. A cookie will also be created autometically with the name of PHPSESSID in the users computer. The  PHPSESSID stores a unique value for each session ID.
  3. The session value is also stored either in the database or in the predefined folder name for which we do the settings in PHP.INI file and set a session path in session.save_path.

So when a request is sent from the browser, then first it looks for the cookie names  PHPSESSID created with the unique sessions ID and then match the session value which is stored either in the database or in the predefined folder. And based on this, the data will retrieved from the server and sent to the browser for that particular user.

How to Start a PHP Session

we need to use a PHP function named session_start() on the top of the page to start a session. This is the first and most important step if you trying to create a session using PHP.

And then the session value will be stored using a PHP global variable named $_SESSION. 

You can understand this using the following example:

PHP Session Example

In this example, we created a session named “username” using the PHP global variable $_SESSION. So now, if we want to retrieve the value of this session on any page then, first thing would be to add the function session_start() on the top of every page and only then you will be able to retrieve the value of session.

How to retrieve the PHP session Value

You can also display the session value using the following method also

How to destroy a session in PHP

If you want to destroy all the PHP sessions then just use the function session_destroy(). Once you call this function, it will automatically destroy all the PHP sessions.

But in case, if you want to destroy any particular session then you need to use the “unset()” function.

You can see both the methods in the following example:

We hope this chapter clears all the basics about the sessions in PHP.

Leave a Reply

Your email address will not be published.