Using a Cookie

Learn how to use cookies.

Array of key-value pairs

The PHP server has a built-in mechanism that takes the Cookie header from the request, processes its contents, and produces a nice array of key/value pairs. The array is a superglobal variable, just like $_GET and $_POST. This one is called $_COOKIE.

Let’s use the name cookie in random.php to personalize the page a bit:

Press + to interact
<h1>Your lucky number is: <?php echo $randomInt; ?></h1>
<?php if ($randomInt > 5) { ?>
<h2>Nice, <?php
echo htmlspecialchars($_COOKIE['name'], ENT_QUOTES);
?>!</h2>
<?php } ?>

Reload the page a few times until it shows a random number higher than 5, after which you should see your name on the screen.

Let’s see how it works ...

Access this course and 1400+ top-rated courses and projects.