Jump to content

[SOLVED] Not getting the update value from cookie


limitphp

Recommended Posts

Ok, I'm pretty confused here.

 

First time users goto my site the variable $time will be emtpy.  Which is fine.  I'll set the default value to 7.

There are links to change the time like so:

http://localhost/website/index.php?time=1

http://localhost/website/index.php?time=7

http://localhost/website/index.php?time=30

etc...

 

When they change the time, I want to set the value in a cookie.

It seems like the value of the cookie is changing, but grabbing it right after I set a cookie doesn't grab the new value.  It grabs the old value.

Here's what the code looks like:

$time = $_GET['time'];
if ($time=='' || !is_numeric($time) || $time>365)
{
  setcookie("time",7, 0);
}else{
  setcookie("time",$time, 0);
}
$time = $_COOKIE['time'];

 

I'm really confused here.  The problem is, when they click to change the time.....say its currently 30 and they click the link to change it to 60.

The cookie changes to 60, but the $time variable stays at 30.

 

Then if they click 90 the cookie changes to 90, but the variable changes to 60.

 

Its like the $time variable is always one behind.

http://us3.php.net/setcookie

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

Doh!

That's what I was afraid of.  There must be someway for me to use two $time variables.  And if they click the link to change it update the $time variable with the get value not the cookie.

I was trying to do that but my logic started going around in circles and I got really confused.

//Get Existing Values
if($_GET['time'])
  $item = $_GET['time'];
elseif($_COOKIE['time'])
  $item = $_COOKIE['time'];
//Validate
if(empty($time) || !is_numeric($time) || $time>365)
  $time = 7;
//Set Cookie for next time
setcookie("time",$time, 0);

//Continue script using $time

//Get Existing Values
if($_GET['time'])
  $item = $_GET['time'];
elseif($_COOKIE['time'])
  $item = $_COOKIE['time'];
//Validate
if(empty($time) || !is_numeric($time) || $time>365)
  $time = 7;
//Set Cookie for next time
setcookie("time",$time, 0);

//Continue script using $time

 

Wait.  What if they have a value in the cookie as 60.  They then click on the link to change it to 30.  Which value does it take?  The Get or the cookie?  Because your if asks get but then says elseif cookie.....in this case both will be true.

Will it take the first one always if both are true?

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.