Lose cookie index on refresh

I’m writing a little in-house script and thought I’d use cookies instead of sessions.

I can’t get the $_COOKIE[‘last’] index to stay after refresh:

<?php
setcookie("user", "Joe", time() + 3600*24);
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
<?php 
$_COOKIE['last'] = "Y";
var_dump($_COOKIE);
?>
</body>

</html> 

On a different script, I simply tried to echo $_COOKIE[‘last’] , but got a notice that it’s not there. var_dump() proves that:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
<?php 
var_dump($_COOKIE);
echo $_COOKIE['last'];

?>
</body>

</html> 

It’s been a while since I worked with cookies. What am I missing?

In the meantime, I’m back to successfully using sessions.

It just occurred to me that cookies wasn’t designed to do that. Like I said, it’s been awhile.

A cookie value is set on http request so in order for a cookie to display you need to redirect somewhere. So setting the cookie then immediately trying to echo it will not work. Try setting it then using a header redirect some where else with a var_dump.

But on the other hand if sessions are working for you and you know how to use them you might as well stick with sessions.

Thanks iamjones.

Turns out that this code will add an index, but I can’t find any documentation on this notation. I’d appreciate any comments or thoughts on this snippet:

$last = $_COOKIE['last'] . ', YEP';
setcookie("last", $last);