How can sessions and cookies be used effectively for user restrictions in PHP?

To implement user restrictions in PHP using sessions and cookies, you can set a session variable upon successful login that indicates the user's authentication status. Then, you can check this session variable on restricted pages to determine if the user is allowed access. Additionally, you can set a cookie with a specific expiration time to remember the user's login status across sessions.

// Start the session
session_start();

// Upon successful login, set a session variable
$_SESSION['authenticated'] = true;

// Check the session variable on restricted pages
if(!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    // Redirect the user or display an error message
    header('Location: login.php');
    exit();
}

// Set a cookie with an expiration time
setcookie('loggedIn', 'true', time() + 3600, '/');