PHP Cookies

Storing data in user's browser

🍪 What are PHP Cookies?

Cookies are small text files stored on the user's computer by the web browser. They remember information about users between page visits, like login status, preferences, and shopping cart items.


<?php
// Create a cookie
setcookie("username", "John", time() + 3600);
echo "Cookie set!";
?>
                                    

Cookie Operations

Creating Cookies

Use setcookie() function to create cookies with name, value, and expiration time. Cookies must be set before any HTML output.

<?php
setcookie("user", "John", time() + 3600);
?>
📖

Reading Cookies

Access cookie values using the $_COOKIE superglobal array. Check if cookie exists before reading to avoid errors.

<?php
if(isset($_COOKIE['user'])) {
    echo $_COOKIE['user'];
}
?>
✏️

Modifying Cookies

Update cookie values by calling setcookie() again with the same name but different value. The new value overwrites the old one.

<?php
setcookie("user", "Jane", time() + 3600);
?>
🗑️

Deleting Cookies

Delete cookies by setting expiration time to the past. This tells the browser to remove the cookie immediately.

<?php
setcookie("user", "", time() - 3600);
?>

🔹 Creating a Cookie

Basic syntax for creating cookies:

<?php
// setcookie(name, value, expire, path, domain, secure, httponly);

// Simple cookie (expires in 1 hour)
setcookie("username", "JohnDoe", time() + 3600);

// Cookie expires in 30 days
setcookie("theme", "dark", time() + (86400 * 30));

// Cookie expires when browser closes
setcookie("session_id", "abc123");

echo "Cookies have been set!";
?>

Cookie Parameters:

  • name - Cookie name (required)
  • value - Cookie value
  • expire - Expiration timestamp
  • path - Server path where cookie is available
  • domain - Domain where cookie is available
  • secure - Only send over HTTPS
  • httponly - Accessible only through HTTP

🔹 Reading Cookie Values

Access cookies using $_COOKIE array:

<?php
// Check if cookie exists
if(isset($_COOKIE['username'])) {
    echo "Welcome back, " . $_COOKIE['username'] . "!";
} else {
    echo "Welcome, new visitor!";
}

// Display all cookies
echo "<h3>All Cookies:</h3>";
foreach($_COOKIE as $name => $value) {
    echo "$name: $value<br>";
}
?>

Output:

Welcome back, JohnDoe!

All Cookies:

username: JohnDoe
theme: dark

🔹 Modifying Cookies

Update existing cookie values:

<?php
// Original cookie
setcookie("counter", "1", time() + 3600);

// Later, update the value
if(isset($_COOKIE['counter'])) {
    $newValue = $_COOKIE['counter'] + 1;
    setcookie("counter", $newValue, time() + 3600);
    echo "Counter updated to: " . $newValue;
}
?>

🔹 Deleting Cookies

Remove cookies by setting expiration to the past:

<?php
// Delete a specific cookie
setcookie("username", "", time() - 3600);
echo "Cookie 'username' has been deleted.";

// Delete all cookies
foreach($_COOKIE as $name => $value) {
    setcookie($name, "", time() - 3600);
}
echo "All cookies deleted!";
?>

🔹 Cookie Expiration Times

Different ways to set cookie expiration:

<?php
// Expires in 1 hour
setcookie("temp", "value", time() + 3600);

// Expires in 1 day
setcookie("daily", "value", time() + 86400);

// Expires in 1 week
setcookie("weekly", "value", time() + (86400 * 7));

// Expires in 1 month
setcookie("monthly", "value", time() + (86400 * 30));

// Expires in 1 year
setcookie("yearly", "value", time() + (86400 * 365));

// Session cookie (expires when browser closes)
setcookie("session", "value");
?>

🔹 Practical Example: Remember Me

Create a "Remember Me" login feature:

<?php
// login.php
if(isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $remember = isset($_POST['remember']);
    
    // Verify credentials (simplified)
    if($username == "admin" && $password == "pass123") {
        
        if($remember) {
            // Remember for 30 days
            setcookie("user", $username, time() + (86400 * 30));
            echo "Logged in! You will be remembered.";
        } else {
            // Session cookie
            setcookie("user", $username);
            echo "Logged in! (Session only)";
        }
    } else {
        echo "Invalid credentials!";
    }
}

// Check if user is already logged in
if(isset($_COOKIE['user'])) {
    echo "Welcome back, " . $_COOKIE['user'] . "!";
}
?>

<!-- Login Form -->
<form method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="checkbox" name="remember"> Remember Me<br>
    <input type="submit" name="login" value="Login">
</form>

🔹 Practical Example: Visit Counter

Track how many times a user visits your site:

<?php
// Check if visit cookie exists
if(isset($_COOKIE['visits'])) {
    $visits = $_COOKIE['visits'] + 1;
} else {
    $visits = 1;
}

// Update cookie (expires in 30 days)
setcookie("visits", $visits, time() + (86400 * 30));

// Display message
if($visits == 1) {
    echo "Welcome! This is your first visit.";
} else {
    echo "Welcome back! You have visited this site $visits times.";
}
?>

Output (on 3rd visit):

Welcome back! You have visited this site 3 times.

🔹 Practical Example: Theme Preference

Save user's theme preference:

<?php
// Handle theme change
if(isset($_GET['theme'])) {
    $theme = $_GET['theme'];
    setcookie("theme", $theme, time() + (86400 * 365));
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Get current theme
$currentTheme = isset($_COOKIE['theme']) ? $_COOKIE['theme'] : 'light';
?>

<!DOCTYPE html>
<html>
<head>
    <style>
        .light { background: white; color: black; }
        .dark { background: #333; color: white; }
    </style>
</head>
<body class="<?php echo $currentTheme; ?>">
    <h1>Current Theme: <?php echo $currentTheme; ?></h1>
    
    <a href="?theme=light">Light Theme</a> | 
    <a href="?theme=dark">Dark Theme</a>
</body>
</html>

🔹 Security Considerations

Make cookies more secure:

<?php
// Secure cookie (HTTPS only)
setcookie("secure_data", "value", time() + 3600, "/", "", true, true);

// Parameters explained:
// - true (6th param) = secure (HTTPS only)
// - true (7th param) = httponly (not accessible via JavaScript)

// Using array syntax (PHP 7.3+)
setcookie("user_token", "abc123", [
    'expires' => time() + 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);
?>

Security Tips:

  • Never store sensitive data (passwords, credit cards) in cookies
  • Use httponly flag to prevent JavaScript access
  • Use secure flag for HTTPS-only transmission
  • Set appropriate expiration times
  • Validate and sanitize cookie data before use

🧠 Test Your Knowledge

Which superglobal array is used to access cookies?