How can PHP sessions and session IDs be leveraged to create a secure authentication system without relying on custom tokens?

Using PHP sessions and session IDs can create a secure authentication system by storing user credentials in the session data and verifying them against a database on each request. This eliminates the need for custom tokens and ensures that authentication is handled securely by PHP's built-in session management.

// Start the session
session_start();

// Check if user is already authenticated
if(isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true){
    // User is authenticated, proceed with the application
} else {
    // User is not authenticated, redirect to login page
    header('Location: login.php');
    exit;
}

// Verify user credentials against a database
// This can be done using a function that checks the credentials
// and sets $_SESSION['authenticated'] to true if they are valid