start learning
Image 1

PHP Sessions

PHP session is a way to preserve data across multiple pages and HTTP requests for a particular user. It allows you to store information on the server that is accessible throughout a user's interaction with your website or web application. PHP sessions are typically used to store user-specific data such as login status, user preferences, and other relevant information.

Here's an example of using PHP sessions with a clarification, including how to set a session after a successful login:

Start a Session

Before you can use sessions in PHP, you need to start a session. This is typically done at the beginning of each script where you want to use sessions. The session_start() function initializes a new session or resumes the existing session.


Please Note: session_start() must be placed at the top of all pages where you want to work with session data. It's essential to call session_start() before any output is sent to the browser, and it should be called on every page where you need to access or modify session variables.

Setting Session Data (After Successful Login)

After a user successfully logs in, you can set session variables to store relevant information about the user. For example, you might want to store the email address.

// Assume $login is true after a successful login
if ($login === true) {
    // Set session variables
    $_SESSION['email'] = $email; // Replace $email with the actual email address

Setting Session Variables ($_SESSION['variable']): After a successful login, you set session variables to store user-specific data. These variables can be accessed on other pages once the session is started.

Accessing Session Data

Now that you've set session data, you can access it on other pages where the session is started. For example, on a dashboard page, you might want to display the email of the logged-in user.


// Check if the user is logged in
if (isset($_SESSION['email'])) {
    // User is logged in
    echo "Welcome, " . $_SESSION['email'] . "!";
} else {
    // Redirect to the login page if not logged in
    header("Location: login.php");

In PHP, a session typically starts when a user accesses a page on a site and a session ID is either received from the user (via a cookie or a URL parameter) or a new session ID is generated. The session_start() function is often used to initiate a session.
Here's a simplified sequence of events during session initialization :

  1. User Accesses a Page
    • When a user accesses a PHP page that calls session_start(), PHP checks for an existing session ID. If one exists (e.g., stored in a cookie or passed in the URL), it's used; otherwise, a new session ID is generated.
  2. Garbage Collection Probability
    • After the session is initialized, the PHP runtime environment considers whether to initiate the garbage collection process. The probability of garbage collection is determined by the session.gc_probability and session.gc_divisor settings in the php configuration or php.ini file. As example e take (session.gc_probability = 1 and session.gc_divisor = 100), there is a 1% chance that garbage collection will run during each session initialization.
  3. Garbage Collection (Possibly)
    • If the conditions for garbage collection are met based on the probability settings, PHP may perform garbage collection. During this process, PHP examines existing session data and removes sessions that have exceeded the session.gc_maxlifetime. Garbage collection helps clean up expired session data, preventing the server from accumulating unnecessary session files.
  4. Session Continues
    • After session initialization and potential garbage collection, the PHP script continues to execute. The session data is available through the $_SESSION superglobal, and a session cookie might be set with a lifetime specified by session.cookie_lifetime.

Destroy a Session (Logout)

When a user logs out, you should destroy the session to ensure that the user is no longer considered logged in.


// Unset all session variables
$_SESSION = array();

// Destroy the session

// Redirect to the login page
header("Location: login.php");

Destroying a Session (session_destroy()): When a user logs out, you destroy the session to ensure that stored data is cleared. This is essential for security.

It's important to consider and be aware of certain php configurations that can affect how sessions are handled. Here are some key php settings related to sessions:

  1. session.save_path
    • Specifies the path where session files are stored on the server. Ensure that the directory is writable by the web server.
  2. session.gc_maxlifetime
    • Sets the maximum lifetime of a session in seconds. After this period, the session is considered garbage and may be cleaned up during the garbage collection process.
  3. session.gc_probability and session.gc_divisor
    • Control the probability of garbage collection. For example, if session.gc_probability is set to 1 and session.gc_divisor is set to 100, there is a 1% chance that garbage collection will be initiated on each session initialization.
  4. session.cookie_lifetime
    • Sets the lifetime of the session cookie in seconds. It determines how long the session cookie will persist on the client's side.
  5. session.cookie_path and session.cookie_domain
    • Define the path and domain for which the session cookie is valid. Ensure that these settings align with your application's structure and requirements.
  6. session.use_cookies and session.use_only_cookies
    • session.use_cookies determines whether the session ID is passed via cookies. Setting session.use_only_cookies to 1 ensures that the session ID is only accepted from cookies and not from other sources like URLs.
  7. session.use_strict_mode
    • When set to 1, it enhances session security by rejecting uninitialized session IDs.
  8. session.auto_start
    • When set to 1, PHP automatically starts a session on every request. This can be useful but may not be necessary in all cases.

Before relying on sessions in your PHP application, review and configure these settings in the php.ini file to match your application's needs. Additionally, be aware that some hosting environments may have restrictions on modifying certain php.ini settings, and in such cases, you may need to use .htaccess or user.ini files to override specific configurations.