How do I get the cookies to persist in php?
give_cookie.php
<?php
if (!isset($_COOKIE["muffin"]))
setcookie("muffin", "55", 100 * 60 * 60 * 24 * 30);
$_COOKIE["lid"]=true;
?>
jar.php
<?php
var_dump($_COOKIE);
if($_COOKIE["lid"])
echo "open";
?>
Running the code in that order gives me output:
array(0) { } Notice: Undefined index: lid in jar.php on line 3
Embedding the code from jar.php
in give_cookie.php
gives me output:
array(1) { ["lid"]=> bool(true) } open
Other answers are right, but there is another consideration. Cookies get set when the server sends the html to the client, and they are received from the user when the user requests the page. That means, if you try to read a cookie you just set correctly, it will be empty until next time the user reloads the page. The only way to avoid this is, as you did, not sure if on purpose or not, to assign manually the cookie's value and set it at the same time since it is a superglobal. This is NOT a good practice since the value of the Cookie gets lost for this execution. This should work but not do much work:
give_cookie.php
jar.php
PS, there are many more problems with your code (besides it does nothing useful). Tell us what you are trying to achieve so we can help you a bit more.
You're supposed to give a UNIX timestamp of when the cookie will expired (calculated since the epoch) as the third argument to the function call.
I suggest you read the documentation for
setcookie
.you're setting the cookie for
muffin
and trying to retrievelid
.you need to setcookie forlid
as well.i think the time you are setting is still in the past
currently
so try