What are the best practices for handling user login and redirection to different pages within a PHP application, particularly in the context of AJAX requests and form submissions?

When handling user login and redirection in a PHP application, it is important to validate user credentials securely, set session variables upon successful login, and redirect users to the appropriate pages based on their authentication status. When dealing with AJAX requests and form submissions, it is crucial to handle the redirection logic on the server-side to ensure a seamless user experience.

// PHP code snippet for handling user login and redirection

session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate user credentials
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // Check if username and password are correct (this is a basic example, actual validation should be more secure)
    if($username === 'admin' && $password === 'password') {
        $_SESSION['loggedin'] = true;
        echo json_encode(['redirect' => 'dashboard.php']);
    } else {
        echo json_encode(['error' => 'Invalid credentials']);
    }
}

// In dashboard.php or any other protected page, check if user is logged in before allowing access
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: login.php');
    exit();
}