Jump to content

PHP Cookie problem


c_pattle

Recommended Posts

I'm having trouble setting a cookie in php.  When a user logs in I send an ajax request to an file which contains this code to set the cookie

 

setcookie("userCookie", $_SESSION['username'], time()+60*60*24*30);

 

However when I include the following code to check to see if the cookie has been set is says is hasn't

 

if(isset($_COOKIE['userCookie'])) {
echo("cookie set");
} else { echo("cookie not set"); }

 

I check to see that my browser is accepting cookies and it definitely is so I'm not sure what causing the problem. 

 

Thanks for any help. 

Link to comment
Share on other sites

1)  Are you sure that variable you're setting exists?  If it's FALSE or 0, it won't go through.

 

2)  $_COOKIE is only populated on subsequent loads of the page.  Set the cookie, visit a new page, cookies are there.

 

3)  Are you seeing the cookies in your browser?  Install the "view cookies" plugin for firefox, then view the cookies in the page information dialog (CTRL+I [i for Information])

 

-Dan

Link to comment
Share on other sites

If you are trying to access the cookie from a different folder than where it's set, it might not be available. You should specify your cookie options in the setcookie statement.

 

setcookie ("myCookie", "myValue", time()+60*60*24*30, '/', '.domain.com');

 

'/' makes it available on all directories under your domain.com

.domain.com makes the cookie available to all subdomains.. if you specify www.domain.com then no subdomains are included, only the default subdomain which is www.

 

Try those and if you can access it after that.. Be more specific of where you need the cookie. Those are instructions for the clients browser on when to send the cookie to you with their http request.

Link to comment
Share on other sites

When I copied the same code into my main index page it works fine but not when it's in another file. 
PHP code can't simply be copied and pasted from one document to another and retain its values.  I bet it's not working when you think it is.  echo "COOKIE SET TO: {$_SESSION['username']}";  I bet it's not there.
Link to comment
Share on other sites

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.