Cookies
A cookie is a small value a site asks a browser to store. The browser sends the value back with later requests, so PHP can read it from the $_COOKIE array.
setcookie hands back true
setcookie takes a cookie name and a value. The var_dump line shows the call handed back true.
<?php
var_dump(setcookie("user", "Hana"));A saved name reads back
A real request would fill $_COOKIE before the program runs. This program fills the array by hand, in the same shape.
<?php
$_COOKIE["user"] = "Hana";
echo "Hello " . $_COOKIE["user"] . "\n";A returning visitor and a first visit
isset tests whether the user key sits in $_COOKIE. The program removes the key with unset, then tests the same array again.
<?php
$_COOKIE["user"] = "Hana";
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"] . "\n";
} else {
echo "First visit\n";
}
unset($_COOKIE["user"]);
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"] . "\n";
} else {
echo "First visit\n";
}Example
<?php
$_COOKIE["user"] = "Hana";
$_COOKIE["theme"] = "dark";
echo "Hello " . $_COOKIE["user"] . "\n";
echo "Theme: " . $_COOKIE["theme"] . "\n";Key points
- Use setcookie to ask the browser to store a cookie under a name.
- The setcookie call in the first snippet hands back true.
- The browser stores the cookie after the response reaches it.
- On a later request, the browser sends stored cookies to the server.
- PHP fills $_COOKIE with the cookies sent in a request.
- A command line run holds no browser, so it cannot store cookies between runs.
In this example, two lines fill $_COOKIE by hand with a user name and a theme. The greeting line reads the user key. The theme line reads the theme key and prints dark.
Note
The hand-filled $_COOKIE values in this lesson show one program viewing one request.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does var_dump(setcookie("user", "Hana")) print in the first snippet?