Amina
Amina's Blog

lorem ipsum

Jul 2, 2024 4 minute read

Storing Data in PHP Sessions

Table of Contents

  1. What are PHP Sessions?
  2. How PHP Sessions Work
  3. Setting up PHP Sessions
  4. Session Security
  5. User Authentication Example
  6. Useful Links

What are PHP Sessions?

PHP sessions are a way to store data between requests, in the $_SESSION superglobal array, to be used across multiple pages.

A visitor accessing your website, is assigned a unique ID, that would be the session ID. This is either stored in a cookie on the user side, or it is propagated in the URL.

Common use cases for sessions are:

  • User authentication
  • Shopping carts
  • User preferences and settings

How PHP Sessions Work

Session Lifecycle

A PHP session starts when the session_start() function is called and ends when session_destroy() is invoked or when the session times out. Each session is identified by a unique session ID, which is typically stored in a cookie on the client side.

Session Variables

Session variables are used to store user-specific data that can be accessed throughout a user's visit to a website.

Setting up PHP Sessions

Starting a Session

To start a session, simply call session_start() at the beginning of your PHP script:

<?php
session_start();
?>

Storing Data in Sessions

You can store data in session variables using the $_SESSION superglobal array:

<?php
session_start();
$_SESSION['username'] = 'john_doe';
?>

Accessing Session Data

To access session data on another page, call session_start() again and use the $_SESSION array:

<?php
session_start();
echo $_SESSION['username']; // Outputs: john_doe
?>

Destroying a Session

To delete all session data, use session_destroy():

<?php
session_destroy();
?>

This command deletes all session data and can be useful if the user wants to log out of your system, for example. Remember, you must first execute session_start() before you can execute session_destroy().

To delete a single session variable, you can use unset($variable):

<?php
unset($_SESSION['name']);
?>

Session Security

Security is crucial when dealing with sessions. To protect user session data from unauthorized access, tampering, and theft, you need to implement certain security measures.

Session Hijacking

Session hijacking involves stealing a user's session ID to impersonate them. To prevent this:

  • Use HTTPS to encrypt data between the client and server
  • Regenerate session IDs periodically using session_regenerate_id()

Session Fixation

Session fixation attacks involve forcing a user to use a known session ID. Prevent this by regenerating session IDs upon login:

<?php
session_start();
session_regenerate_id(true); // Regenerate session ID to prevent fixation
?>

Other session security measures include:

  • Setting session timeouts to expire inactive sessions automatically
  • Setting appropriate session cookie parameters using session_set_cookie_params()
  • Storing sensitive session data securely on the server side
  • Input validation, authentication and access control

For more information on session security, check out this blog post.

User Authentication Example

Here's a simple user authentication example using sessions:

// login.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate credentials (this is a simplified example)
    if ($username == 'admin' && $password == 'password') {
        $_SESSION['username'] = $username;
        header('Location: dashboard.php');
    } else {
        echo 'Invalid credentials';
    }
}
?>

<!-- login.html -->
<form method="POST" action="login.php">
    Username: <input type="text" name="username">
    Password: <input type="password" name="password">
    <button type="submit">Login</button>
</form>

// dashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.html');
    exit();
}

echo 'Welcome, ' . $_SESSION['username'];
?>

Amina