0

I have the following code:

<?php
$cookie_name = "offer";
$cookie_value = "signup";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

When I open the page in a browser the cookie is not set. When I then refresh the page the cookie is set.

Why is it not set on the first page load?

Thank you.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
Pete D
  • 311
  • 3
  • 15
  • 1
    "Why is it not set on the first page load?" — Because the browser didn't send the cookie to the server for that request. – Quentin Jun 28 '17 at 08:41

1 Answers1

1

$_COOKIE contains the cookies that have been sent with the request. Since you only set the cookie afterwards (when the request has been received), $_COOKIE does not contain the cookie. However the cookie is set successfully (check with your browser for example)

dlaxar
  • 549
  • 1
  • 4
  • 9