Sessions
Imagine you're shopping online. You add a few items to your cart and continue browsing. How does the website remember what items you've put in your cart even if you visit different pages? This "memory" is made possible through something called "sessions".
In simple terms, a session in PHP (or any other web programming language) is a way to store information about a user's activity or choices temporarily so that this information can be accessed across multiple pages of a website. It's like the website giving you a special locker to store your stuff while you shop around.
Sessions are temporary
When you close your browser, or after a certain period of inactivity, the session data is deleted.
How sessions work
Behind the scenes, sessions use cookies. The main difference is that PHP keeps track of sessions for you. Let's break it down.
First Request
When a client accesses a website for the first time, it doesn't have any session information. Recognizing this, the server initiates a new session. This involves generating a unique identifier known as the "session ID."
The server sends this session ID back to the client's browser in the form of a cookie (typically named PHPSESSID
for PHP sessions). The browser stores this cookie, which contains the session ID.
Subsequent Requests
Whenever the client makes subsequent requests to the same server, it automatically sends along the session cookie (with the session ID).
Upon receiving a request with a session ID, the server fetches the corresponding session data from its storage. This session data is like a small storage bin associated with that particular session ID. It's used to store and retrieve data about that user's session, like user preferences, logged-in status, or items in a shopping cart.
The server processes the request using this session data, ensuring a consistent and personalized experience for the user. If any updates are made to the session data, those are saved on the server side.
The client continues to automatically send the session ID with every request as long as the session is active.
Session Expiry or Termination
Sessions don't last forever. They have a lifetime, which can be configured on the server. After a certain period of inactivity, a session will expire. When this happens, its data is deleted from the server.
Alternatively, sessions can be manually terminated using server-side commands.
If a client makes a request after a session has expired or been destroyed, the process starts over: the server sees it as a new session, generates a new session ID, and sends it back to the client.
Initializing a Session
Sessions are started using the session_start()
function. This function initializes a new session or resumes an existing one. It should be called before any output is sent to the browser, typically at the very top of your PHP script.
session_start();
If you don't call session_start()
, you won't be able to access or set session variables.
Working with Session Data
After you've started a session using session_start()
, you can access or update session data using the $_SESSION
superglobal array.
To access session data, you simply refer to the $_SESSION
array with the relevant key.
session_start();
// Assuming 'username' was previously set in the session
if(isset($_SESSION['username'])) {
echo "Logged in as: " . $_SESSION['username'];
} else {
echo "Not logged in.";
}
In this example, the isset()
function checks if the username
key exists in the $_SESSION
array before trying to access it. This is a good practice to prevent potential errors or notices.
Updating session data is as straightforward as setting a new value for an existing key in the $_SESSION
array.
session_start();
// Updating the 'username' session variable
$_SESSION['username'] = 'JaneDoe';
After this code runs, the username
value in the session will be changed to 'JaneDoe'
.
To add new data to the session, just create a new key-value pair in the $_SESSION
array.
session_start();
// Adding a new session variable
$_SESSION['user_role'] = 'admin';
If you want to remove specific data from the session without destroying the entire session, you can use the unset() function.
session_start();
// Removing 'username' from the session
unset($_SESSION['username']);
After this code runs, the 'username'
key and its associated value will be removed from the session.
Sessions available on the server only
The session data is stored on the server, not on the client's machine. The client only holds a session ID, which is used to access the corresponding session data on the server.
Completely Destroying Session Data
To completely destroy session data, you'll want to use a combination of methods to ensure the session data is removed both from the $_SESSION
superglobal array and from the server's storage.
The $_SESSION
superglobal array holds all session variables. To clear it, you can use the session_unset()
function or simply unset the $_SESSION
array itself.
// Option 1: Using session_unset()
session_unset();
// Option 2: Directly unsetting the $_SESSION array
// unset($_SESSION);
To completely remove the session data from the server storage, use the session_destroy()
function.
session_destroy();
Clear the Session Cookie (Optional but Recommended)
While session_destroy()
removes the session data on the server, the session cookie may still exist on the client side. If you want to ensure the session ID cookie is removed as well, you can clear it.
if(isset($_COOKIE[session_name()])){
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
In the above example, we're checking if the session exists by using $_COOKIE[session_name()]
. Session IDs are always stored in a cookie. If you want the cookie name, you can use the session_name()
function.
After checking it exists, you can proceed to delete the cookie by using the setcookie()
function. To properly delete the cookie, we're grabbing the cookie settings for the session, which can be accessed via the session_get_cookie_params()
function. As we call the setcookie()
function, we're setting the time to a value in the past to ensure the browser deletes the cookie.
Key Takeaways
- Use
session_start()
to initiate or resume a session. Always call this before any output (headers, HTML, etc.). - Session data is stored in the
$_SESSION
superglobal array. - To remove a specific session variable:
unset($_SESSION['key']);
. - To clear all session variables without ending the session:
session_unset();
. - To destroy a session completely, use
session_destroy()
. This removes the session data from the server. - Working with sessions in PHP is an essential skill for creating interactive and personalized web applications.