How can cookies and sessions be effectively used for user authentication in PHP?
Cookies can be used to store a unique identifier for a user upon successful login, while sessions can store additional user information securely on the server side. By setting a cookie with the user's identifier and storing relevant user data in a session upon login, you can authenticate users across multiple pages within a PHP application.
// Start the session
session_start();
// Check if user is logged in
if(isset($_SESSION['user_id'])){
// User is logged in, retrieve user data from session
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];
// Additional user data can be stored and retrieved here
} else {
// User is not logged in, redirect to login page
header("Location: login.php");
}
// Set a cookie with the user's identifier
setcookie("user_id", $user_id, time() + (86400 * 30), "/"); // Cookie expires in 30 days