What are the best practices for managing session timeouts in PHP to redirect users to the homepage after a period of inactivity?

Session timeouts in PHP can be managed by setting the session expiration time and checking for user activity to reset the timer. To redirect users to the homepage after a period of inactivity, you can use a combination of session variables and JavaScript to track user activity and redirect them when the session expires.

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

// Set session expiration time to 30 minutes
$session_expiration = 1800;

// Check if session variable for last activity time is set
if(isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > $session_expiration) {
    // Redirect user to homepage
    header("Location: index.php");
    exit();
}

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