What are some best practices for handling session variables in PHP to prevent them from being destroyed unexpectedly?

Session variables in PHP can be unexpectedly destroyed if the session expires or if the user closes the browser. To prevent this, you can set the session cookie to have a longer expiration time and regenerate the session ID periodically to prevent session fixation attacks. Additionally, you can store critical session data in a database or use other persistent storage methods.

// Set session cookie to have a longer expiration time
ini_set('session.cookie_lifetime', 86400); // 1 day

// Regenerate session ID periodically
if (mt_rand(1, 100) == 1) {
    session_regenerate_id();
}

// Store critical session data in a database
$_SESSION['user_id'] = 123; // Example of storing user ID in session