Why can't I set a cookie?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
skypanther
Forum Newbie
Posts: 7
Joined: Thu Jun 02, 2005 3:19 pm

Why can't I set a cookie?

Post by skypanther »

I'm trying to set a cookie on a site I'm developing. Right now, the site is running off of localhost (IIS5) but the same behavior is exhibited when I publish to my demo server (RedHat w/ Apache).

I've tried with both FireFox and IE6. I DO NOT have cookies blocked. Just to be sure, I added localhost to the allowed-to-set-cookies list in FireFox. No change.

Here's the statement I'm using:

setcookie("skipsurvey","yes",time()+60*60*24*365,"/");

I've also tried:

setcookie("skipsurvey","yes");
setcookie("skipsurvey","yes",time()+60*60*24*365);
setcookie("skipsurvey","yes",time()+60*60*24*365,"/","localhost",0);
and $_COOKIE['skipsurvey'] = 'yes';

I can set session variables, but I want the data to stick around rather indefinitely so I think a cookie better suits my needs.

Nothing, zippo. No cookie. print_r($_COOKIE) shows it's not there, as does if(isset($_COOKIE['skipsurvey']))...

I'm sure it's a stupid error I've made, but I just don't see it.

Tim
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

are you checking the cookie on that page load, or on a different page load.. because the cookie data won't exist until the next page loads.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

and make sure you set the cookie before anything is printed to the browser, and before any white space in your script
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
skypanther
Forum Newbie
Posts: 7
Joined: Thu Jun 02, 2005 3:19 pm

Post by skypanther »

Thanks to both of you. I found the mistake, and as I suspected it was a dumb thing on my part. I was trying to set a cookie and redirect (with header('location:...')) all on the same page. I struggled with the page for hours and had to leave and let my head clear before I finally figured out what I was doing wrong.

Thanks,
Tim
Post Reply