faqts : Computers : Programming : Languages : PHP : Common Problems : Cookies

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

92 of 104 people (88%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I create a cookie that works with both www.mydomain.com and mydomain.com?
Is a cookie set for www.mydomain.com sent in a query to mydomain.com?
How do I create a cookie thatreconise if a user has already seen the intro of a site,so that when
Could you please give me a few steps on how to create this cookie?

Jul 3rd, 1999 19:49
Nathan Wallace, unknown unknown, Gale T, Flint Doungchak, Tom Henry, Jim Winstead, Steve Lianoglou


Cookies only work for the exact domain name that they are set.  For
example:

  SetCookie("Cookie",$value,"time()+3600","/dir/","www.mydomain.com",0);

sets a cookie that will only ever be sent by the client to the server if
the server domain name is *www.mydomain.com.  The client looks to see if
the cookie domain matches exactly the tail end of the request domain.

Reading the Netscape Cookie Specification:

    http://home.netscape.com/newsref/std/cookie_spec.html

you will learn that the domain in the cookie must contain two periods
(.).  This is to prevent people setting a cookie that might be sent to
every .com domain for example.  That means that a cookie like this:

  SetCookie("Cookie",$value,"time()+3600","/dir/","mydomain.com",0);

will not be remembered by the browser.

This is a problem because often people access the same site using both:

    http://www.mydomain.com
    http://mydomain.com

so neither of the cookie setting techniques above will work.

You can set a single cookie that will work for both of these domains by
including a leading period in the domain name.

  SetCookie("Cookie",$value,"time()+3600","/dir/",".mydomain.com",0);

The difference is that ".domain.com" sets a domain-wide cookie (which
will be sent to http://domain.com, http://www.domain.com, and
http://whatever.domain.com). Without the leading ".", it will only
get sent to that specific hostname.

An alternative solution, is to redirect people who log in to

    http://mydomain.com

to the site (with www.mydomain.com cookie):

    http://www.domain.com

but this may inconvenience some users.