Try this quick little demo, as it shows you the use of cookies. This demo is implemented using JavaScript, but today we'll do talk about cookies and PHP.
Cookies are used to store information on the client side, in the browser. This is data that the webserver wants/needs to know about, but the server will not store the data internally, and HTTP is a state-less protocol. There are quite a few use cases for this. We could store information that records who you are, such as an authentication token. It is also useful for pages that use shopping carts, and in a very common use case, to track you across websites (3rd party cookies) to support ads.
The browser automatically sends the relevant cookies to the server during each request, and the server needs to define new, or modify existing, cookies before any real content is sent back to the user. In fact, cookies must be set before any other content is provided to the user, because the cookie data is sent in the HTTP response header, using the set-cookie key, not in the HTTP response body. Therefore you should set the cookies before any output is produced, including <!DOCTYPE html>.
To set a cookie in PHP, we use the setcookie() function, which takes as parameterrs the name and value for the cookie. We can optionally add an expiration date, path for which the cookie is valid, a domain that the cookie is available to, and other security related parameters. Example:
<?php
// Grab a value from the form
$name = $_POST['username'];
// Set the time to expire to be 86400 seconds from now (aka in 24 hours)
//expires is given as a Unix timestamp - seconds since epoch
$expires = time() + 86400;
// Set the value.
setcookie("username", $name, $expires);
?>
To read the cookies received from the browser (not the ones just set using setcookie()), we use the PHP superglobal variable $_COOKIE. Example:
<?php
// if "Name" exists, do something:
if (isset($_COOKIE["username"])) {
$name = $_COOKIE["username"];
echo "<h1>Hello $name, it is nice to see you again.</h1>";
}
?>
To delete a cookie, we set the cookie with an expiration date in the past. Example:
<?php
// Set the time to expire in the past
$expires = time() - 100;
// Set the value.
setcookie("username","", $expires);
?>
We mentioned that all relevant cookies are sent by the browser to the server.
Hopefully you have already run the little demo at the top of the lecture. Currently the value of the $_COOKIE supervariable (as seen by the server) is:
Array
(
[color] => blue
[animal] => dogs
[food] => donuts
[name] => null
)
rand() or random_int(min, max).