Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Advertisement
  1. Code
  2. PHP

How to Use Sessions and Session Variables in PHP

by
Read Time:14 minsLanguages:

Session handling 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 handling 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.

Cookies vs. Session Variables

Not sure if you need cookies or session variables? Session variables are a way to store data about a user in a database and retrieve it later. Cookies are a way to store data about a user on the user's computer. Session variables are typically used in applications that need to keep track of a user's activity. Cookies are typically used in applications that need to store information about a user for a single site.

You can also learn about session variables in my post on using cookies in PHP.

What Is a Session in PHP?

A session is a mechanism to persist information across 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 a specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing the 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.

The HTTP Protocol and a Stateless RequestThe HTTP Protocol and a Stateless RequestThe HTTP Protocol and a Stateless Request

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 come into the picture.

A session allows you to share information across 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 common login flow for a website to understand what happens behind the scenes.

  1. A user opens the login page of a website.
  2. After submitting the login form, a server on the other end authenticates the request by validating the credentials that were entered.
  3. 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.
  4. 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.
  5. 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 this PHPSESSID cookie, which stores the session id passed by the server.
  6. For subsequent requests, the PHPSESSID cookie is passed back to the server. When the server comes across the PHPSESSID cookie, it will try to initialize a session with that session id. It does so by 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 multiple requests, and the user is kept logged in throughout a session.

The following diagram depicts how the HTTP protocol works with sessions.

The HTTP Protocol and a Request With SessionsThe HTTP Protocol and a Request With SessionsThe HTTP Protocol and a Request 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'll see most often, where a session is started by the session_start function.

The important thing is that the session_start function must be called at 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 request—session.auto_start. By default, it’s set to 0, and you can set it to 1 to enable the auto startup functionality.

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.

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.

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.

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.

As you can see, we’ve started a session at 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 the server which was created when the session was started. In this way, the session data is shared across 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 expires when the browser is closed.

How to Modify and Delete Session Variables

You can modify or delete session variables created earlier in the application in the same way as for regular PHP variables.

Let’s see how to modify the session variables.

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.

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.

The session_destroy function deletes everything that’s stored in the current session. Having said that, it doesn't unset global variables associated with the session or unset the session cookie.

So if you're using the session_destroy function to log a user out, you must unset the $_SESSION variable and unset the session cookie as well. Thus, the recommended way to destroy a session completely is:

Session Handlers

So far, we've discussed how you can perform different operations with session variables. In this section, we'll discuss what a session handler is and how you can use it.

A PHP session handler is a mechanism which instructs PHP how it should manage sessions. The default session handler is a file system, and it means that PHP stores sessions on the disk. Basically, it's a small file on the server which is associated with the unique session id. It's the same id which is stored in a session cookie on the client browser.

The default session handler in PHP provides you with all the features that are needed, but sometimes you want to store sessions differently. For example, you might want to manage sessions in a database, Redis, or some other storage. In this case, you need to implement a custom session handler which overrides the default behavior.

To understand how custom session handlers work, we'll briefly discuss how you can implement a database session handler which manages sessions in a MySQL database.

How to Implement a Database Session Handler

In the PHP session lifecycle, there are different stages like open, read, write, and close. Additionally, there are two more stages: destroy and garbage collection. So when you implement a custom session handler, you have to handle each of these stages to manage the session data properly.

There are two ways you could implement a custom session handler, Either you could define callback functions for different stages in the session lifecycle or you could write a class which implements the SessionHandlerInterface interface. In both cases, you need to use the session_set_save_handler function to initialize your custom session handler. In our case, we’ll use the SessionHandlerInterface interface implementation.

In our example, we’re going to store sessions in the MySQL database. So let’s create a table which stores the session data by using the following snippet.

Next, let’s see how our custom database session handler looks:

Our custom session handler class MySQLSessionHandler implements the SessionHandlerInterface interface. Thus, it must implement methods that are declared in the SessionHandlerInterface interface. We'll look at these methods one by one to understand how each one works.

First, to use this code, make sure to replace the HOST_NAMEUSERNAME, and other placeholders with actual values in the __construct method.

When the session is started, the open method is called. It returns TRUE if the database connection was successful. If there was any problem setting up the database connection, it returns FALSE.

Next, PHP calls the read method to read the session data. The read method receives the session id as the first argument. We’ll check if there’s any entry available for this session id in the session_data table. If it exists, we’ll return the session data; otherwise, an empty string will be returned.

When PHP needs to save or close a session, it calls the write method. It’s used to write the session data in a database. We’ve used the REPLACE syntax to make sure that if an entry exists, it will be updated; otherwise, it’ll be inserted.

The close method is called after the session write method has been called. It works similar to a destructor in classes. In our case, there is nothing particular that needs to be done in the close method.

The destroy method is called when the session is destroyed with either the session_destroy or session_regenerate_id function. In this method, the session data is deleted from a database if it exists.

When PHP runs the garbage collector periodically, the gc method is called. The $lifetime variable holds the value of the session.gc_maxlifetime configuration option in the php.ini file. In this method, we’ll delete all sessions that are expired as a part of the garbage collection process.

Using the MySQL Session Handler Class

Now, let’s see how to use the MySQLSessionHandler handler class.

As you can see, we just need to initialize the MySQLSessionHandler class and pass it to the session_set_save_handler function to instruct PHP that it needs to use the MySQLSessionHandler class for session management. Next, we’ve called the session_start function to start a session. Finally, we’ve initialized a session variable for testing purposes.

If everything goes well, you should see the session entry in the sessions table as shown in the following screenshot.

And with that, you’ve created a working custom session handler which manages sessions in a database!

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 sessions, and later on we created a few PHP examples to demonstrate how you could create and destroy sessions as well as manipulating session variables.

A related topic is cookies. You can learn how to use cookies in PHP right here at Envato Tuts+!

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.