Sessions - potatoscript/php GitHub Wiki

Session Management in PHP

Overview

Sessions are a way to store information (in variables) to be used across multiple pages. Unlike cookies, the data is stored on the server rather than the client, making it more secure. PHP provides built-in functions to manage sessions and user data.

In this section, we will cover:

  • Starting a Session
  • Storing Session Data
  • Retrieving Session Data
  • Modifying Session Data
  • Destroying a Session
  • Session Security Best Practices

Starting a Session

To start using sessions in PHP, you must call the session_start() function at the beginning of your script (before any output is sent to the browser). This function creates a session or resumes the current session based on a session identifier passed via a GET or POST request or in a cookie.

Example:

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

// Set a session variable
$_SESSION["user_name"] = "JohnDoe";

// Access the session variable
echo "Hello, " . $_SESSION["user_name"];
?>

Explanation:

  • session_start() initializes a session or resumes the existing one.
  • $_SESSION is a global associative array used to store session data.

Storing Session Data

Once a session is started, you can store any type of data in the $_SESSION superglobal array. This data will be accessible throughout the session, even after page reloads.

Example:

<?php
session_start();

// Store user information in session variables
$_SESSION["username"] = "JaneDoe";
$_SESSION["email"] = "[email protected]";
?>

Explanation:

  • We store two pieces of information, username and email, into session variables.

Retrieving Session Data

After the session is started, you can retrieve session data by accessing the $_SESSION superglobal array.

Example:

<?php
session_start();

// Retrieve session data
echo "Username: " . $_SESSION["username"];
echo "Email: " . $_SESSION["email"];
?>

Explanation:

  • We access the session variables username and email to display their values.

Modifying Session Data

Session data can be modified at any time during the session. You can update an existing session variable or add new ones.

Example:

<?php
session_start();

// Modify session data
$_SESSION["username"] = "JohnSmith";
echo "Updated Username: " . $_SESSION["username"];
?>

Explanation:

  • We update the session variable username to a new value.

Destroying a Session

If you no longer need the session, you can destroy the session completely by calling session_destroy(). This removes all session data stored on the server. However, calling session_destroy() does not automatically unset session variables. You should also unset them using unset().

Example:

<?php
session_start();

// Unset all session variables
session_unset();

// Destroy the session
session_destroy();

// Redirect the user after logging out
header("Location: login.php");
exit();
?>

Explanation:

  • session_unset() removes all session variables.
  • session_destroy() destroys the session on the server.
  • After logging out, it's common to redirect the user to a login page using header().

Session Security Best Practices

While sessions are secure by default, there are a few steps you can take to enhance session security:

1. Regenerate Session ID

To prevent session fixation attacks, it's a good practice to regenerate the session ID during sensitive actions (like login).

<?php
session_start();

// Regenerate session ID
session_regenerate_id();
?>

2. Use Secure Cookies

You can configure PHP to store session data in cookies securely by setting appropriate flags.

<?php
// Start the session with secure cookie settings
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true, // Only send cookie over HTTPS
    'httponly' => true, // Prevent JavaScript access to session cookie
    'samesite' => 'Strict' // Restrict cookie to same-site requests
]);
session_start();
?>

3. Set Custom Session Save Path

By default, PHP stores session data in the /tmp directory on the server. To improve security, you can specify a custom session save path.

<?php
// Set a custom session save path
session_save_path('/path/to/custom/session/directory');
session_start();
?>

4. Session Timeout

You can implement session timeouts by checking the session's last activity time. If the session has been idle for a certain period, you can log the user out.

<?php
session_start();

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

// Check if the session has expired
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout_duration)) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}

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

Explanation:

  • $_SESSION['last_activity'] stores the timestamp of the last user action.
  • If the session is idle for more than 30 minutes, the session is destroyed, and the user is redirected to the login page.

Conclusion

In this section, we covered how to:

  • Start and manage sessions in PHP.
  • Store, retrieve, modify, and destroy session data.
  • Implement session security by regenerating session IDs, using secure cookies, setting custom save paths, and implementing timeouts.

By following these best practices, you can ensure that your PHP application maintains secure and efficient session management, which is crucial for handling user authentication and maintaining user states across page visits.