User Sessions
Learn what sessions are, how to use them in PHP, and how to avoid common session-related pitfalls.
Let’s look at another data storage mechanism—user sessions. They’re more stable than cache, but they have short-term persistence too.
What are user sessions?
Sessions are a data store for short-term user-specific data. For example, imagine Alice opens a website and logs in. The information that stores the fact she has logged in as a specific user needs to be preserved across multiple requests, so she stays logged in after refreshing the page. This information is short-term—if she opens the same website the next day, she’ll have to log in again. And, this information is user-specific, so if Bob opens the same website on another computer, he won’t be logged in as Alice. Take a second to admire how great that is.
How PHP stores sessions
It uses a key-value store with long semi-random keys, one for each user. The key is called session ID, and the value is session data. When a user starts a new session, the server generates a random 26-character (char) session ID and sets a PHPSESSID
cookie containing the newly generated session ID. It also creates a temporary file for storing session data. On every new request, user also sends a cookie with session ID, and the server loads the session data from the matching file. The default session lifetime is 24 minutes since the last request.
The user doesn’t have direct access to the session data, so it’s safe to use sessions to store dangerous data like the current user ID. We can customize all the details like the session ID cookie name, the session ID value, and a lifetime.
A session cookie is the only way for the server to determine the session owner. Anyone with the same session cookie will be considered a logged-in user. That’s why session cookies are secret and hackers want to steal them. It would be a bad idea to use predictable session IDs.
Using PHP session storage
To start working with the session, first, we need to call the function session_start()
. After this, we can access and modify the session data by working with the global array $_SESSION
.
Here’s an example that counts from 42
. This time, we store the data in a session.
Get hands-on with 1400+ tech skills courses.