How can PHP developers implement time-based session management, such as automatic logout after a period of inactivity, in their web applications using cookies?

To implement time-based session management in PHP using cookies for automatic logout after a period of inactivity, developers can set a timestamp in the cookie when the user logs in and then check this timestamp against the current time on each page load. If the time difference exceeds a certain threshold (indicating inactivity), the user can be automatically logged out.

// Set timestamp in cookie when user logs in
setcookie('login_time', time(), time() + (86400 * 30), '/');

// Check timestamp on each page load
if(isset($_COOKIE['login_time'])) {
    $inactive_time = 1800; // 30 minutes of inactivity
    if(time() - $_COOKIE['login_time'] > $inactive_time) {
        // Perform logout actions, such as destroying session variables
        session_destroy();
        // Redirect user to login page
        header('Location: login.php');
        exit();
    } else {
        // Update timestamp to current time
        setcookie('login_time', time(), time() + (86400 * 30), '/');
    }
}