views:

162

answers:

6

Ok I have a cookie set, and I can clearly see it if I go to private data in Firefox... ok so when I echo it on one page in a certain directory it works, (www.example.com/dir), but on the index page of the site (www.example.com), it wont echo, it says the cookie is not set. Yes I have cookies enabled, yes I tried clearing cache and all that. Any ideas? PHP btw

+1  A: 

You need to check the path that the cookie is being set.

If it's not '/', there's your answer!

Jacob Relkin
+3  A: 

Which directory are you in when the cookie gets set?

From the PHP manual on setcookie(), emphasis mine:

Path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

Pekka
+2  A: 

Cookies can be bound to a specific domain, subdomain, path, and protocol (http/https). You need to specify the path when setting the cookie in PHP:

setcookie("TestCookie", "Value", time()+3600 , '/' );

The fourth parameter binds it to the root of the site and it will be available in any subdirectory of the main site.

If you want it available on the main domain and any subdomain, supply the fifth parameter like this:

setcookie("TestCookie", "Value", time()+3600 , '/', '.example.com' );

Now it will be readable at:

www.example.com
example.com/newdir
awesome.example.com/newdir

Doug Neiner
A: 

You need to set the $path to / in setcookie(), if you want to access it in all directories

Joel L
+1  A: 

Set your path option; the default value is the current directory that the cookie is being set in. Because you're setting the cookie in the directory /dir , its only available within that directory or below it.

You get around this by explicitly setting the path, ie.

setcookie(name,value,expire,path,domain,secure) 

Set the path to "/".

Erik
I type WAY too slow.
Erik
A: 

Ok lol you guys got it thanks!

David
This is not a place for comments. (This here is)
Joel L