Skip to content
PHP Logo

What are common pitfalls when using sessions in PHP scripts?

Common pitfalls when using sessions in PHP scripts include not starting the session before using session variables, not properly handling session expiration and regeneration, and not properly securing session data to prevent session hijacking.

php
<?php
// Start the session before using session variables
session_start();

// Handle session expiration and regeneration
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['last_activity'] = time();
}

// Secure session data to prevent session hijacking
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
?>