What are the best practices for handling user authentication and redirection in PHP scripts?

When handling user authentication and redirection in PHP scripts, it is important to securely validate user credentials before allowing access to protected resources. It is also crucial to properly handle redirection after successful authentication to direct users to the appropriate pages based on their role or permissions.

// Check if user is authenticated before granting access to protected resources
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Redirect users based on their role or permissions after successful authentication
if ($_SESSION['role'] == 'admin') {
    header('Location: admin_dashboard.php');
    exit();
} elseif ($_SESSION['role'] == 'user') {
    header('Location: user_dashboard.php');
    exit();
}