0

I tried to write a code that set a cookie and check if isset this cookie show massage "cookie create" else show "cookie not create" but it not work this code in localhost work correctly.

<html>
<head>
<?php setcookie("a","abcdef",time()+3600); ?>
</head>
<body>
<?php 
phpinfo(); 

if(isset($_COOKIE['a']))
{
echo $_COOKIE["a"];
}
else
{
echo "no cookie";
}
?>
</body>
</html>
DeiDei
  • 10,205
  • 6
  • 55
  • 80
  • 1
    Possible duplicate of [PHP - setcookie(); not working](https://stackoverflow.com/questions/20316870/php-setcookie-not-working) – pspatel May 28 '18 at 17:56
  • no this question dont solve my problem –  May 28 '18 at 18:01

1 Answers1

0

As answered by this other question on Stack Overflow, PHP - setcookie(); not working, your PHP application is emitting HTML output before attempting to set the cookie:

<html>  <------- oh no!
...
<?php setcookie("a","abcdef",time()+3600); ?>

At this point, PHP has already finished sending the HTTP headers (not to be confused with the HTML <head> tag) and the cookie cannot be set (which must be done as part of the HTTP headers).

Set the cookie first and you should be fine:

<?php setcookie("a","abcdef",time()+3600); ?>
<html>
...

Be certain you are calling setcookie() before any other (non-HTTP-header) output.

DaveGauer
  • 1,255
  • 14
  • 25