Session handing is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In this post, you’ll learn the basics of session handing in PHP. We’ll start with an explanation of how sessions work and how they are related to cookies. Then we’ll look at a few code snippets that demonstrate how to work with sessions. You’ll learn how to create and destroy sessions, and how to change session variables.
What is a Session in PHP?
A session is a mechanism to persist information across the different web pages to identify users as they navigate a site or app. Are you wondering why sessions are needed for a website? To see why sessions are necessary, we have to go back and see how the HTTP protocol is designed to work.
The HTTP protocol is a stateless protocol, which means that there’s no way a server can remember the specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing contents of the requested page. So when you access other pages of the same website, the web server interprets each and every request separately, as if they were unrelated to one another. There’s no way for the server to know that each request originated from the same user.
The following diagram depicts the HTTP protocol in a nutshell.
In this model, if you wanted to display user-specific information, you’d have to authenticate a user in each request. Imagine if you had to type your username and password on every page that displayed your profile information! Yes, it would be cumbersome and not practical at all, and that’s where sessions comes into the picture.
A session allows you to share information across the different pages of a single site or app—thus it helps maintain state. This lets the server know that all requests originate from the same user, thus allowing the site to display user-specific information and preferences.
Login Flow With Sessions and Cookies
Let’s quickly go through a usual login flow for a website to understand what happens behind the scenes.
- A user opens the login page of a website.
- After submitting the login form, a server on the other end authenticates the request by validating the credentials that were entered.
- If the credentials entered by the user are valid, the server creates a new session. The server generates a unique random number which is called a session id. It also creates a new file on the server which is used to store the session-specific information.
- Next, a session id is passed back to the user, along with whatever resource was requested. Behind the scenes, this session id is sent in the
PHPSESSID
cookie in the response header. - When the browser receives the response from the server, it comes across the
PHPSESSID
cookie header. If cookies are allowed by the browser, it will save thisPHPSESSID
cookie which stores the session id passed by the server. - For subsequent requests, the
PHPSESSID
cookie is passed back to the server. When the server comes across thePHPSESSID
cookie, it will try to initialize a session with that session id. It does so loading the session file which was created earlier during session initialization. It will then initialize the super-global array variable$_SESSION
with the data stored in the session file.
In this way, the user data is preserved across the multiple requests and the user is kept logged in throughout a session.
The following diagram depicts how the HTTP protocol works with sessions.
Now that you’ve seen a brief introduction to how sessions work, we’ll create a few practical examples to demonstrate how to create and manipulate session variables.
How to Start a Session
In this section, we’ll discuss how to start a session in PHP.
Whenever you want to deal with session variables, you need to make sure that a session is already started. There are a couple of ways you can start a session in PHP.
Use the session_start
Function
This is the method that you’l see most often, where a session is started by the session_start
function.
<?php // start a session session_start(); // manipulate session variables ?>
The important thing is that the session_start
function must be called in the beginning of the script before any output is sent to the browser. Otherwise, you’ll encounter the infamous Headers are already sent
error.
Automatically Start a Session
If there’s a need to use sessions throughout your application, you can also opt-in to starting a session automatically without using the session_start
function.
There’s a configuration option in the php.ini file which allows you to start a session automatically for every requests—session.auto_start
. By default, it’s set to 0
, and you can set it to 1
to enable the auto startup functionality.
session.auto_start = 1
On the other hand, if you don’t have access to the php.ini file, and you’re using the Apache web server, you could also set this variable using the .htaccess file.
php_value session.auto_start 1
If you add the above line in the .htaccess file, that should start a session automatically in your PHP application.
How to Get a Session Id
As we discussed earlier, the server creates a unique number for every new session. If you want to get a session id, you can use the session_id
function as shown in the following snippet.
<?php session_start(); echo session_id(); ?>
That should give you the current session id. The session_id
function is interesting in that it can also take one argument—a session id. If you want to replace the system generated session id with your own, you can supply it to the first argument of the session_id
function.
<?php session_id(YOUR_SESSION_ID); session_start(); ?>
It’s important to note that the session_id
function must be placed before the session_start
call when you want to start a session with a custom session id.
How to Create Session Variables
In this section, we’ll explore how to initialize session variables in PHP.
As we discussed earlier, once a session is started, the $_SESSION
super-global array is initialized with the corresponding session information. By default, it’s initialized with a blank array and you can store more information by using a key-value pair.
Let’s go through the following example script that demonstrates how to initialize session variables.
<?php // start a session session_start(); // initialize session variables $_SESSION['logged_in_user_id'] = '1'; $_SESSION['logged_in_user_name'] = 'Tutsplus'; // access session variables echo $_SESSION['logged_in_user_id']; echo $_SESSION['logged_in_user_name']; ?>
As you can see that, we’ve started a session in the beginning of the script using the session_start
function. Following that, we’ve initialized a couple of session variables. Finally, we’ve accessed those variables using the $_SESSION
super-global.
When you store the data in a session using the $_SESSION
super-global, it’s eventually stored in a corresponding session file on a server which was created when the session was started. In this way, the session data is shared across the multiple requests.
As we discussed, the session information is shared across requests, and thus the session variables initialized on one page can be accessed from other pages as well, until the session expires. Generally, a session is expired when the browser is closed.
How to Modify and Delete Session Variables
You can modify or delete session variables created earlier in the application the same way as for regular PHP variables.
Let’s see how to modify the session variables.
<?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 1; } else { ++$_SESSION['count']; } echo $_SESSION['count']; ?>
In the above script, we’ve checked if the $_SESSION[‘count’]
variable is set in the first place. If it’s not set, we’ll set it to 1
, otherwise we’ll increment it by 1
. So, you if refresh this page multiple times, you should see that the counter is incremented by one every time!
On the other hand, if you would like to delete a session variable, you can use the unset
function as shown in the following snippet.
<?php // start a session session_start(); // initialize a session variable $_SESSION['logged_in_user_id'] = '1'; // unset a session variable unset($_SESSION['logged_in_user_id']); ?>
Thus, you can no longer access the $_SESSION[‘logged_in_user_id’]
variable as it’s deleted by the unset
function. So that’s how you can alter the session information.
How to Destroy a Session
In this section, we’ll see how you could destroy a session. In the previous section, we discussed the unset
function which is used if you want to delete specific session variables. On the other hand, if you want to delete all session related data at once, you can use the session_destroy
function.
Let’s try to understand how it works using the following example.
<?php // start a session session_start(); // assume that we’ve initialized a couple of session variables in the other script already // destroy everything in this session session_destroy(); ?>
The session_destroy
function deletes everything that’s stored in the current session. Thus, you will see a blank $_SESSION
variable from the subsequent requests as the session data that was stored on the disk was deleted by the session_destroy
function.
Generally, you would use the session_destroy
function when the user is being logged out.
Conclusion
In this article, we’ve explored the basics of session handling in PHP. It’s a key concept which allows you to persist information across web pages.
In the first half of the article, we discussed the basic concepts of session and later on we created a few PHP examples to demonstrate how you could create and destroy sessions as well as manipulate session variables.