What are the recommended methods for redirecting users to a login page after a session timeout occurs during an Ajax request in PHP applications?

When a session timeout occurs during an Ajax request in PHP applications, one recommended method is to check the session status before processing the Ajax request. If the session has timed out, redirect the user to the login page. This can be achieved by sending a specific response back to the client-side JavaScript code, which can then handle the redirect.

<?php
// Check session status before processing Ajax request
session_start();
if (isset($_SESSION['user_id'])) {
    // Process Ajax request
    // Your code here
    echo json_encode(['success' => true]);
} else {
    // Session has timed out, redirect user to login page
    http_response_code(401);
    echo json_encode(['error' => 'Session timeout']);
}
?>