Sessions in PHP work by creating a unique session identifier for each user, which is stored on the server. This identifier is sent to the user's browser as a cookie, allowing the server to retrieve session data as the user navigates through the site. This capability is essential for applications that require user authentication, shopping carts, or any feature that needs to remember user-specific information.

Starting a Session

To use sessions in PHP, you must start a session using the session_start() function. This function must be called before any output is sent to the browser. Here’s an example of how to start a session:

<?php
// Start the session
session_start();

// Set a session variable
$_SESSION['username'] = 'JohnDoe';

// Output the session variable
echo 'Session variable is set to: ' . $_SESSION['username'];
?>

Key Points:

  • Always call session_start() at the beginning of your script.
  • Session variables are stored in the $_SESSION superglobal array.

Storing Data in a Session

Once a session is started, you can store various types of data in the session. Here are some examples of storing different data types:

<?php
session_start();

// Storing different types of data
$_SESSION['username'] = 'JohnDoe'; // String
$_SESSION['user_id'] = 101; // Integer
$_SESSION['is_logged_in'] = true; // Boolean
$_SESSION['cart'] = ['item1', 'item2', 'item3']; // Array

// Output session data
echo 'User ID: ' . $_SESSION['user_id'] . '<br>';
echo 'Is Logged In: ' . ($_SESSION['is_logged_in'] ? 'Yes' : 'No') . '<br>';
echo 'Cart Items: ' . implode(', ', $_SESSION['cart']);
?>

Best Practices for Session Data:

  • Store only essential data in sessions to minimize memory usage.
  • Avoid storing sensitive information directly in session variables. Instead, use user IDs or hashed data.

Retrieving Session Data

Retrieving session data is straightforward. You simply access the $_SESSION array using the key associated with the data you want to retrieve. Here’s an example:

<?php
session_start();

// Check if the user is logged in
if (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in']) {
    echo 'Welcome back, ' . $_SESSION['username'] . '!';
} else {
    echo 'Please log in to access this page.';
}
?>

Handling Session Expiration

Sessions can expire after a certain period of inactivity. You can control session expiration by setting session timeout values. Here’s a simple way to implement session expiration:

<?php
session_start();

// Set session timeout duration (in seconds)
$timeout_duration = 1800; // 30 minutes

// Check if the session variable for last activity is set
if (isset($_SESSION['LAST_ACTIVITY'])) {
    // Calculate the session's lifetime
    if (time() - $_SESSION['LAST_ACTIVITY'] > $timeout_duration) {
        // Session has expired
        session_unset(); // Unset session variables
        session_destroy(); // Destroy the session
        echo 'Session expired. Please log in again.';
        exit;
    }
}

// Update last activity time
$_SESSION['LAST_ACTIVITY'] = time();
?>

Destroying a Session

When a user logs out or when you need to clear session data, you can destroy the session using session_destroy(). Here’s how to do it:

<?php
session_start();

// Unset all session variables
$_SESSION = [];

// Destroy the session
session_destroy();

echo 'You have been logged out.';
?>

Important Note:

  • Always unset session variables before destroying the session to ensure that data is cleared properly.

Summary of Session Management

FeatureDescription
Start a Sessionsession_start()
Store Data$_SESSION['key'] = value;
Retrieve Dataecho $_SESSION['key'];
Check for Existenceisset($_SESSION['key']);
Destroy a Sessionsession_destroy();
Handle ExpirationUse a timestamp to track last activity

Conclusion

Sessions are an essential feature in PHP for managing user state across web applications. By following the best practices outlined in this tutorial, you can effectively use sessions to enhance user experience while maintaining security.

Learn more with useful resources: