PHP - Create cookie

by
Jeremy Canfield |
Updated: January 04 2021
| PHP articles
Create cookie using PHP in the head of your HTML.
<head>
<?php
$cookie_key = "foo";
$cookie_value = "bar";
setcookie($cookie_key, $cookie_value, time() + (86400 * 30), "/");
?>
</head>
The following can then be in the body of your HTML to show if the cookie was created.
<body>
<?php
if(!isset($_COOKIE[$cookie_key])) {
echo "Cookie '" . $cookie_key . "' is not set";
}
else {
echo "Cookie is set<br>";
echo "Cookie key = " . $cookie_key . "<br>";
echo "Cookie value = " . $_COOKIE[$cookie_key] . "<br>";
}
?>
</body>
Or, cookies are created by starting a session. Refer to PHP - Secure web pages using sessions. Add the following PHP to the pages that you want to use sessions.
<?php
session_start();
?>
When navigating to a page that includes session_start(), a cookie will be created in the web browser with a unique session ID number.
Did you find this article helpful?
If so, consider buying me a coffee over at