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
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.
The time the cookie expires. This is a Unix timestamp so is in number
of seconds since the epoch. In other words, you'll most likely set
this with the time() function plus the number of seconds before you
want it to expire. Or you might use mktime(). time()+60*60*24*30 will
set the cookie to expire in 30 days. If set to 0, or omitted, the
cookie will expire at the end of the session (when the browser
closes).
I suggest you read the documentation for setcookie
.
you're setting the cookie for muffin
and trying to retrieve lid
.you need to setcookie for lid
as well.
i think the time you are setting is still in the past
currently
time() = 1348584550
100 * 60 * 60 * 24 * 30 = 259200000
so try
setcookie("muffin", "55", time() + (100 * 60 * 60 * 24 * 30));
if($_COOKIE["muffin"])
echo "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
<?php
if (!isset($_COOKIE["muffin"]))
setcookie("muffin", "55", 100 * 60 * 60 * 24 * 30);
setcookie("lid", TRUE, time() + 100 * 60 * 60 * 24 * 30);
$_COOKIE["lid"]=TRUE;
?>
jar.php
<?php
if($_COOKIE["lid"])
echo "open";
?>
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.