← Back to PHP Course | Chapter 12: Sessions & Cookies | Lesson 4 of 5

PHP Cookie Management

Introduction to Cookies

setcookie() is the function that actually creates a cookie on the visitor's machine; it takes the cookie's name and value plus optional settings that control its lifetime, scope, and security.

Example: Introduction to Cookies

php
<?php
setcookie("username", "Alice");
echo "Cookie created with a name and value";
?>

Setting Cookie Expiration

If you don't pass an expiration time to setcookie(), the cookie is treated as a session cookie and disappears the moment the browser closes -- explicitly setting a future timestamp is what makes data persist across visits.

Example: Setting Cookie Expiration

php
<?php
setcookie("username", "Alice"); // session cookie -- disappears when browser closes
setcookie("remembered_user", "Alice", time() + 86400); // persists for 1 day
echo "Two cookies set with different lifetimes";
?>

Cookie Security Options

Marking a cookie HttpOnly stops client-side scripts from reading it (blocking a common XSS attack path), while marking it Secure ensures the browser only ever transmits it over an encrypted HTTPS connection.

Example: Cookie Security Options

php
<?php
setcookie("token", "abc123", ['httponly' => true, 'secure' => true]);
echo "HttpOnly blocks JS access; Secure requires HTTPS";
?>

Deleting Cookies

Setting a cookie's expiration to a timestamp in the past is the standard way to delete it, since there's no dedicated delete function -- the browser sees the expired date and discards the cookie on its next check.

Example: Deleting Cookies

php
<?php
setcookie("username", "", time() - 3600);
echo "Expiration set in the past -- cookie will be discarded";
?>

Checking if Cookies are Enabled

You can test cookie support by setting a throwaway cookie on one page load and checking for its presence on the next; if it's missing, the visitor's browser likely has cookies disabled or blocked.

Example: Checking if Cookies are Enabled

php
<?php
setcookie("test_cookie", "1");
if (isset($_COOKIE['test_cookie'])) {
    echo "Cookies are enabled";
} else {
    echo "Cookies may be disabled -- check on next page load";
}
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.