How does PHP handle session IDs in different scenarios, such as browser requests versus xmlhttprequests?

PHP handles session IDs differently depending on the type of request being made. When a browser makes a request, PHP automatically manages the session ID through cookies. However, when making requests using XMLHttpRequest (AJAX), the session ID needs to be manually passed in the headers to maintain the session state.

// Start the session
session_start();

// Check if session ID is present in the headers
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    if(isset($_SERVER['HTTP_SESSION_ID'])) {
        session_id($_SERVER['HTTP_SESSION_ID']);
    }
}

// Continue with your PHP code