Consider this PHP script that sets a cookie and then tries to read it immediately:
<?php
setcookie('user', 'Alice', time() + 3600);
if (isset($_COOKIE['user'])) {
echo 'User is ' . $_COOKIE['user'];
} else {
echo 'No user cookie found';
}
?>What will this script output when run for the first time in a browser?
<?php setcookie('user', 'Alice', time() + 3600); if (isset($_COOKIE['user'])) { echo 'User is ' . $_COOKIE['user']; } else { echo 'No user cookie found'; } ?>
Remember that cookies are sent by the browser on the next request, not immediately.
When you set a cookie with setcookie(), it sends a header to the browser. The cookie is not available in $_COOKIE until the next page load because the browser must send it back in the request headers.
When a server wants to store a cookie on a user's browser, which HTTP response header does it use?
Think about the header sent from server to client to store data.
The server uses the Set-Cookie header to tell the browser to store a cookie. The browser then sends the cookie back in the Cookie header on future requests.
Look at this PHP code that tries to delete a cookie:
<?php
setcookie('session', '', time() - 3600);
if (isset($_COOKIE['session'])) {
echo 'Session cookie exists';
} else {
echo 'Session cookie deleted';
}
?>What will this script output when run immediately after the cookie was set previously?
<?php setcookie('session', '', time() - 3600); if (isset($_COOKIE['session'])) { echo 'Session cookie exists'; } else { echo 'Session cookie deleted'; } ?>
Think about when the cookie is actually removed from $_COOKIE.
Setting a cookie with a past expiration date tells the browser to delete it, but $_COOKIE still contains the cookie data for the current request. The cookie will be gone on the next request.
Consider this PHP code snippet:
<?php
setcookie('theme', 'dark');
echo $_COOKIE['theme'];
?>When run, it sometimes shows a warning: Undefined index: theme. Why?
<?php setcookie('theme', 'dark'); echo $_COOKIE['theme']; ?>
Think about when cookies become available in PHP.
Cookies set by setcookie() are sent to the browser in headers. The browser sends them back on the next request. So, $_COOKIE does not contain the new cookie until the next page load.
A website sets these cookies with these paths:
- Cookie A: path=/
- Cookie B: path=/shop
- Cookie C: path=/shop/sale
If the browser requests the URL https://example.com/shop/sale/item1, how many cookies will be sent to the server?
Cookies are sent if the request path starts with the cookie's path.
All three cookies have paths that match the request URL path. The request path /shop/sale/item1 starts with /, /shop, and /shop/sale, so all three cookies are sent.