Jump to content

Trouble learning to use cookies..


Jack.Straw

Recommended Posts

Hi.  I'm learning PHP and can't seem to figure out how to use cookies properly.  Can anyone tell me what i'm doing wrong here?
[code]<?
if (isset($_COOKIE["user"]))
  $user=$_COOKIE["user"];
else
  $user="Guest";
  $name="Jack;
  $life="36000";
  setcookie('user', $name, $life);
?>

<html>
<head>
<title>.</title>
</head>
<body>
<? echo "Hello $user"; ?>
</body>
</html>[/code]

It's supposed to say "Hello Guest" the first time you visit, then say "Hello Jack" when you reload the page.  Can anyone tell me why?

Thanks in advance!
-Jack
Link to comment
https://forums.phpfreaks.com/topic/26173-trouble-learning-to-use-cookies/
Share on other sites

The proplem is in how you are defining the life value. Check the manual: http://us3.php.net/manual/en/function.setcookie.php

It states "Expire: The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch."

The "epoch" is some time in 1970 I think. So, you have set the expiration to be 36,000 seconds after that time. So, the cookie is expired as soon as you set it. Try setting:

$life = time()+36000;

That will make the cookie expire in 36,000 seconds from the time it is set - or 10 hours.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.