- How to Use Sessions and Session Variables in PHP
- Cookies vs. Session Variables
- What Is a Session in PHP?
- Login Flow With Sessions and Cookies
- How to Start a Session
- Use the session_start Function
- PHP Session
- In this article
- What is a PHP Session
- Creating a PHP Session
- Viewing the PHP Session ID
- Updating PHP Session Variables
- Destroying the Session
- Key Takeaways
How to Use Sessions and Session Variables in PHP
Sajal Soni Last updated Feb 16, 2021
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.
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.
- 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 this PHPSESSID 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 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.
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.
PHP Session
What is a session and how is it managed? In this article, we’re going to look at sessions: starting a session, the session id, session variables and ending a session. We’ll go through an example that uses a single page to demonstrate saving/persisting information in sessions across page requests. Every request for a web page in PHP, even if that request is multiple times for the same page, is an independent request which does not automatically save data for use between those requests. In essence, sessions solves that problem.
In this article
What is a PHP Session
A session is a way for you to persist (save) information between requests, PHP does this by uniquely identifying users, using what is called a session cookie.
For example: A user visits your website and is served the home page, index.php. The same user requests the very same home page again a few minutes later (or a different page on your PHP website)
- How can PHP save variables between pages: for the same page request, or between different page requests?
- How can PHP identify a specific user? (We need to uniquely identify each user if we want to save data between requests)
Session variables: these are the variables we would like to save between requests, it’s up to you to decide what variables to save to the session, depending on your requirements.
Creating a PHP Session
Now that we have a basic understanding of sessions, we can go through example session code. We will keep our example as simple as possible to get a better understanding of session management.
Our example will use a single PHP page that is visited repeatedly by the same user. We can apply the same concepts to multiple pages and different users. Below is our initial code, it displays the number of times a user visited our page.
For now, our code does not work as we expect: requesting/refreshing the page does not update the variable $pageVisitCount.
Let’s update our code to begin using sessions, start the session by calling the session_start function. The session start function, starts a new session or resumes an existing session. It will return TRUE if the session was successfully started.
We call session_start on our first line of code, we store the return value of session_start in the variable sessionStarted . We can then check if the session did actually start and run the appropriate code, in our case: to display the text ‘Session started’.
We can control the session timeout or cookie lifetime by passing the cookie_lifetime option to the session_start function.
For the above example, our session will be valid for 30 days from the last time our session was started or resumed, not from the time the session was first started.
Viewing the PHP Session ID
After successfully starting a session, the user who requested the page is assigned a unique session id. We can view the session id by calling the function session_id. Let’s display the session id for our own educational purposes, you won’t display session id’s in a production environment for security reasons (the user can however view their own session id in a cookie saved to the user’s browser)
Updating PHP Session Variables
Now that our session is started we can save variables to the session. In PHP, you access and set session variables using the global $_SESSION . If we wanted to save a variable $person to the session, we could give it a key person . Our code would then be: $_SESSION[‘person’] = $person; The key can be named anything you want, but meaningful names are good practice.
We’ve updated our code to save the variable $pageVisitCount to the session with the key pageVisitCount , the assignment is $_SESSION[‘pageVisitCount’] = $pageVisitCount .
We retrieve the value from the session with the code $pageVisitCount = $_SESSION[‘pageVisitCount’] and use a default of 0 if the value was not previously saved to the session.
Destroying the Session
Our code now uses the session to save and retieve variables for use on our web page. The last addition for our example would be to use session_destroy to end the session and clear the variables which were saved to the session.
We call session_destroy(); when the $pageVisitCount reaches a value of 10 . In a real world example, you would typically call session_destroy(); when a user signs out of a restricted access system.
Key Takeaways
- Start or resume a session using session_start , and check the return value to confirm whether the session did actually begin.
- To increase or decrease the session validity period, use the option cookie_lifetime when starting the session.
- session_id can be used to view the unique session id, which can also be viewed by users in their browser.
- Use session_destroy to end a session.
- The session example we looked at, went from start to finish of session management using a single page. As an exercise, you could write an in-depth code example using multiple PHP pages.
This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.