Skip to content
PHP Logo

What is the best practice for managing session IDs in PHP to avoid clutter and inefficiency?

To avoid clutter and inefficiency when managing session IDs in PHP, it is recommended to regenerate session IDs periodically or after a certain number of requests. This helps prevent session fixation attacks and reduces the likelihood of session hijacking.

php
// Regenerate session ID every 30 minutes or after 100 requests
if (!isset($_SESSION['created'])) {
    $_SESSION['created'] = time();
    $_SESSION['requests'] = 0;
} else {
    $_SESSION['requests']++;
    if (time() - $_SESSION['created'] > 1800 || $_SESSION['requests'] > 100) {
        session_regenerate_id(true);
        $_SESSION['created'] = time();
        $_SESSION['requests'] = 0;
    }
}