PDA

View Full Version : Cookies


oracleguy
01-14-2003, 04:21 PM
I have a question about using cookies with PHP.

I set a cookie with the SetCookie function, right?

And from what I understand to retrieve the value you just call it like a variable like $mycookiename , right?

But when I do this, if I attempt to get the cookie's value on a page before anything has been set, I get an error because the variable isn't defined when i try to see if the cookie has a value.

So what am I missing?

Thanks in advance.

mordred
01-14-2003, 04:35 PM
Better check that the variable has been set in the first place and use the super-global $_COOKIE array, like this (assumes your variable in the cookie goes by the name of "foo":


if ( isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar' ) {
// do something
}

oracleguy
01-14-2003, 04:48 PM
Ah I see I'll try that out when I get home.

oracleguy
01-15-2003, 12:12 AM
Okay it works... but only in that browser window... If i close the window and open it back up again, it doesn't remember the cookie.

Here is code I am using to set the cookie:
SetCookie('AlreadyVoted','yes');

And here is the if statement seeing if the cookie has been set... cuz what I'm doing is if it isn't set then it displays the form and if it is set it doesn't show the form.
if (!isset($_COOKIE['AlreadyVoted']) && $_COOKIE['AlreadyVoted'] != 'yes')

See for yourself, the poll is the thing I'm working on. www.oregonlan.ws/index-2.php

mordred
01-15-2003, 01:25 PM
When you set the cookie, you have to set the expiration time also, or the cookie will be deleted when the browser is closed (like session cookies). I remember that the manual had good examples in the user notes, FWIW.

oracleguy
01-15-2003, 04:05 PM
Oh! Okay. I'll try that out.

goog
01-15-2003, 07:55 PM
here (http://perl.about.com/library/weekly/aa051600a.htm) is a really great tutorial about cookies in php. It's very short and concise, and you can probably skip the first page which explains about WHAT a cookie is, just look at the examples on the next pages about setting, deleting, and retrieving a cookie.