View Full Version : how to overcome the pitfalls of php cookies?

01-30-2007, 07:55 AM
i need to set a cookie and work with that cookie on the same page.

this seem to be not possible with php cookies:

"Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter."

how to overcome this?
is this possible using other programming languages such as cgi, perl so that we can set cookies and read them and process them on the same page?

please point me to such tutorials.

thank you very much.

01-30-2007, 08:12 AM
i wonder what would be the point of being able to do that? why do you
need to set a cookie and work with that cookie on the same page.
You just do all your processing first to determine the value that your cookie needs to have, and then you set it.

the cookie-collection is part of the http-header, so if you set a cookie then it first needs to be sent to the browser, and on any consecutive pagerequest for that domain, that cookie will be added to the http-header (until it expires).

01-30-2007, 09:02 AM
Since the whole point of cookies is to pass info between pages I can't imagine any language implementing a means of accessing the cookie again on the same page unless it was just a side effect of the way that they implemented cookies in the language in which case they will probably fix it in the next version so that it no longer has that side effect.

01-30-2007, 04:26 PM
The value/variable that you used to set the cookie is available anywhere on that page, just use that value.

$cookie_value = 'something from somewhere';
setcookie("TestCookie", $cookie_value, time()+3600);

// more code ....

if($cookie_value == 'something from somewhere'){
} // end of !isset cookie...If you have a single web page that has logic to both set a cookie and logic that makes use of that cookie, you can "fake" setting the cookie by adding something like the following after the actual setcookie(...) statement -

$_COOKIE['TestCookie'] = $cookie_value;The key for proper logic when a web page both sets and uses a cookie is that it should have conditional logic that determines what to do when the cookie is set and when it is not set.

01-30-2007, 05:47 PM
Hello raf, felgall, CFMaBiSmAd
thank you very much for your replies.
i have got the code working.
and implemented what i wanted to.
thank you.