views:

49

answers:

3

My friend and I are creating a cookie-based login system using PHP and MySQL, in which when a user logs in, a cookie storing their login information is saved. The problem is, for each URL, http://thewebsite.com and http://www.thewebsite.com, separate cookies are stored.

Is there a solution that would allow us to save the same cookie for multiple URLs, or would we have to redirect the user to http://www.thewebsite.com every time.

If so, what is an easy way of checking whether the 'www' exists in the URL, and redirecting accordingly?

+3  A: 

Have a look at the domain parameter: http://php.net/manual/en/function.setcookie.php It exactly describes the scenario you're having.

Fge
+3  A: 

use the domain argument to setcookie

domain

The domain that the cookie is available to. To make the cookie available on all subdomains of example.com (including example.com itself) then you'd set it to '.example.com'. Although some browsers will accept cookies without the initial ., » RFC 2109 requires it to be included. Setting the domain to 'www.example.com' or '.www.example.com' will make the cookie only available in the www subdomain.

bemace
A: 

If you’re using setcookie and do not specify a domain in the domain parameter, setcookie will not set the corresponding Domain parameter in the Set-Cookie header field (this also applies to session.cookie_domain).

Now if no Domain parameter is present, the user agent defaults the domain value to the to the request-host (see RFC 2109 section 4.3.1):

The user agent applies these defaults for optional attributes that are missing:

  • Domain – Defaults to the request-host. (Note that there is no dot at the beginning of request-host.)

If there is a Domain parameter present, its value must begin with a dot, otherwise the user agent will reject the cookie (see RFC 2109 section 4.3.2):

To prevent possible security or privacy violations, a user agent rejects a cookie (shall not store its information) if any of the following is true:

  • The value for the Domain attribute contains no embedded dots or does not start with a dot.

So, as also described on the setcookie manual page, use .example.com if you want to make your cookie available on example.com and its subdomains, and do not specify a domain if you only want to make it available on the current domain.

Gumbo