Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cookies...arrrrrghhh

Status
Not open for further replies.

JamieFuller

Programmer
Joined
May 2, 2001
Messages
20
Location
GB
I have written a script.

here is the code:

Code:
if(isset($_COOKIE["cartId"])) 
{ 
 echo $_COOKIE["cartId"]; 
}else{ 
 session_start(); 
 setcookie("cartId", session_id(), time() + ((3600 * 24) * 30)); 
echo session_id(); 
}


I understand that cookies are not available until the next page load but why when I press refresh do I get a new value?




Kindest Regards
Jamie
 
Because session variables and cookies are not the same thing. And they are handled differently by PHP.

A cookie stores a value on the client's system. A session stored an index to a set of values on the system.

If you want to use session variables, typically you invoke session_start(), then manipulate the $_SESSION superglobal array directly.

If you need to change the session ID, then use the PHP function session_id() (


Want the best answers? Ask the best questions: TANSTAAFL!
 
Hi sleipnir214,

Thanks for your response however I understand they are different but the code simply copies the session_id() into a cookie variable (if the cookie variable is empty),

then on the next refresh of the page it should see that the cookie has a value in it and return that instead of the session_id().

Seems logical to me?


Kindest Regards
Jamie
 
Your code should work as you think it should.

I've modified that code to read:
Code:
<?php

if(isset($_COOKIE[&quot;cartId&quot;])) 
{
	print 'from cookies: '; 
	echo $_COOKIE[&quot;cartId&quot;]; 
}
else
{ 
	session_start(); 
	setcookie(&quot;cartId&quot;, session_id(), time() + ((3600 * 24) * 30)); 
	print 'from session: ';
	echo session_id(); 
}

?>

When I first run the script I get something along the lines of:

from session: a42087006c3249331019fc4c0a2ca0ba

And in successive runs of the script I get:

from cookies: a42087006c3249331019fc4c0a2ca0ba


I am running PHP 4.3.1 as a module of Apache 1.3.27. My browser is Opera 7.11

Want the best answers? Ask the best questions: TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top