What are the advantages of using sessions over cookies for user authentication in PHP?
Using sessions for user authentication in PHP is more secure than using cookies because session data is stored on the server rather than on the client side. This means that sensitive information, such as user credentials, is not exposed to potential security risks. Additionally, sessions provide more control over the expiration and management of user authentication, making it a more reliable method for verifying user identities.
// Start a session
session_start();
// Check if user is authenticated
if(isset($_SESSION['user_id'])){
// User is authenticated, proceed with actions
} else {
// User is not authenticated, redirect to login page
header("Location: login.php");
exit();
}