PHP

Configure Secure PHP Session Management

Secure PHP sessions by configuring crucial `session_start()` options like `HttpOnly`, `Secure`, and `SameSite` flags, preventing session hijacking and protecting user authentication.

<?php
// It's crucial to call session_start() *before* any output is sent to the browser.

// 1. Force sessions to use cookies, not URLs (prevents session fixation via URL rewriting)
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1); // Only accept session IDs from cookies

// 2. Set secure cookie parameters for session cookies
// This makes the session cookie more resistant to various attacks.
session_set_cookie_params([
    'lifetime' => 3600, // Session lifetime in seconds (e.g., 1 hour)
    'path' => '/', // The path for which the cookie is valid
    'domain' => '.yourdomain.com', // Replace with your actual domain, e.g., 'example.com'
                                   // Prepend with a dot for subdomains if needed, otherwise omit for specific domain.
    'secure' => true, // IMPORTANT: Transmit cookie only over HTTPS (production)
    'httponly' => true, // IMPORTANT: Prevent JavaScript access to the cookie (prevents XSS cookie theft)
    'samesite' => 'Lax' // IMPORTANT: Mitigates CSRF attacks. Options: 'Lax' (default, good balance), 'Strict', 'None'
                       // 'None' requires 'secure' => true
]);

// 3. Start the session
session_start();

// 4. Regenerate session ID on login/privilege escalation (prevents session fixation)
// Example: After a successful login, call session_regenerate_id(true);
if (!isset($_SESSION['initiated'])) {
    session_regenerate_id(true); // Generates a new session ID and deletes the old one
    $_SESSION['initiated'] = true;
}

// Example session usage
if (!isset($_SESSION['views'])) {
    $_SESSION['views'] = 0;
}
$_SESSION['views']++;

// echo "Page views: " . $_SESSION['views'] . "
";

// Example of login logic (simplified)
// if (isset($_POST['username']) && isset($_POST['password'])) {
//     // Authenticate user...
//     if ($authenticated) {
//         session_regenerate_id(true); // Regenerate ID after successful login
//         $_SESSION['user_id'] = $userId;
//         $_SESSION['username'] = $_POST['username'];
//         // Redirect to dashboard or home page
//     }
// }
?>
How it works: This PHP snippet outlines essential steps for secure session management. It configures `session_set_cookie_params` to enforce `HttpOnly` (preventing JavaScript access to session cookies and mitigating XSS-based session theft), `Secure` (ensuring cookies are only sent over HTTPS), and `SameSite` (protecting against Cross-Site Request Forgery - CSRF). Additionally, it ensures sessions use only cookies and demonstrates `session_regenerate_id(true)`, which is crucial for preventing session fixation attacks, especially after a user logs in or their privilege level changes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs