How can the PHP setcookie function be effectively utilized for user authentication in web development projects?

To implement user authentication in web development projects using the PHP setcookie function, you can set a cookie containing a unique identifier for the user upon successful login. This cookie can then be checked on subsequent page loads to verify the user's authentication status.

// Set a cookie upon successful login
$user_id = 123; // Replace with actual user ID
setcookie('user_id', $user_id, time() + 3600, '/'); // Cookie expires in 1 hour

// Check for the presence of the cookie on subsequent page loads
if(isset($_COOKIE['user_id'])) {
    // User is authenticated
    $user_id = $_COOKIE['user_id'];
    // Additional logic to retrieve user data or perform actions
} else {
    // User is not authenticated, redirect to login page
    header('Location: login.php');
    exit();
}