Bits & Bytes

Posts Tagged ‘subdomains’

PHP Cookies, Domains, and Subdomains (oh my!)

Programming in PHP on the web is always interesting, and working with cookies is no exception. For instance, you can set a cookie like this:

setcookie(“a”, “123”);

where “a” is the name and “123” is the value of the cookie.¬† Then you would probably expect it to be available wherever¬† you go in your domain, which we’ll call http://example.com. (Note: do not expect your cookie information to be available if you go to a page on another domain, such as http://myothersite.com). However, what happens when you have a link on your page that takes you to one of your subdomains, like http://subsite.example.com? The page in the subdomain needs the cookie you set, but when you arrive at the new page, the cookie is empty. What happened?

Even though crossing from http://example.com to http://subsite.example.com may not seem like much, it is to a cookie. Cookies are not, by default, available across the subdomains of your domain.

So, when you are on http://example.com, you can set your cookie with name “a” and value “123” and expect it to be available on any page that has http://example.com as part of its URL. However, if you want your cookie to be available as well on http://subsite.example.com, or on all of your subdomains and in any of your directories on your domain, you will need to add a few parameters to the call to setcookie(), like this:

setcookie(“a”, “123”, 0, “/”, “.example.com”);

  1. “a” is the name of the cookie
  2. “123” is the value of the cookie
  3. 0 is the time of expiration. The default is 0, which means the cookie will expire at the end of the session, which is when the browser closes.
  4. “/” refers to where this cookie works. Setting it to “/” will make it available over the entire domain specified in #5. Otherwise, it will be set for the directory that your script is in, which may not be desired.
  5. “.example.com” is the domain over which this cookie remains valid. Adding the “.” to the front of “example.com” will keep the cookie valid over all subdomains of the domain. Do not put “www” in this parameter unless you want the cookie to be valid only over the domain “www.example.com”. If you do, any page with an “example.com” URL then will not have access to the cookie.

Always remember: you must set a cookie before printing any output to the browser.

This function call will return true if the cookie was successfully set, false otherwise.