What is the best practice for setting and maintaining cookies in PHP for user authentication?

Setting and maintaining cookies for user authentication in PHP involves securely storing a unique identifier in a cookie upon successful login and checking this identifier on subsequent requests to verify the user's authentication status. It is important to set the cookie with appropriate security measures, such as HttpOnly and Secure flags, to prevent attacks like XSS and session hijacking.

// Set cookie upon successful login
$unique_identifier = generate_unique_identifier(); // Function to generate a unique identifier
setcookie('auth_cookie', $unique_identifier, time() + 3600, '/', '', true, true); // Setting cookie with HttpOnly and Secure flags

// Verify user authentication on subsequent requests
if(isset($_COOKIE['auth_cookie'])) {
    $stored_identifier = $_COOKIE['auth_cookie'];
    // Check if $stored_identifier is valid and matches user's identifier in the database
    if(is_valid_identifier($stored_identifier)) {
        // User is authenticated
    } else {
        // User is not authenticated, redirect to login page
        header('Location: login.php');
        exit();
    }
} else {
    // User is not authenticated, redirect to login page
    header('Location: login.php');
    exit();
}