简体   繁体   中英

setcookie function and phpinfo in php not working but in localhost work

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM