What potential pitfalls should be avoided when trying to redirect users based on session status in PHP?
When redirecting users based on session status in PHP, it's important to avoid potential pitfalls such as not properly checking if a session has been started or not handling redirect loops. To solve this, always check if a session has been started before attempting to access session variables or redirect based on session status.
<?php
session_start();
if(isset($_SESSION['user_id'])) {
// User is logged in, redirect to dashboard
header("Location: dashboard.php");
exit();
} else {
// User is not logged in, redirect to login page
header("Location: login.php");
exit();
}
?>