BastiaanWW
BastiaanWW

Reputation: 1301

Domain setting not working with php when using setcookie

I have a problem with setting a cookie for a specific domain other which is different from the domain of the website that is generating the cookie.

The following code with a domain provided doesn't work:

setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/','www.domain.com', false);

when I change the above code into this the cookie is set with the domain of my server:

setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/');

Any help is very much appreciated!

Upvotes: 1

Views: 2361

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161447

Unfortunately, this won't work if the site setting the cookie is not the same one being browsed. Otherwise there would be nothing stopping a malicious person from setting random cookies. You could visit some random page and have it overwrite all of your cookies, logging you out of every site you were logged into, as a basic example.

The domain argument of setcookie is meant to specify a domain related to the one being browsed, to allow them to have access to the cookie. For example, when you log into Google calendar, even though you might be viewing your calendar at http://calendar.google.com, the cookie is set with a domain of .google.com, which means that if you went to http://mail.google.com, you would still be logged in. If the calendar program set the cookie domain to .calendar.google.com, then you would have to log in separately when you visited http://mail.google.com.

The documentation mentions this stuff, but it's fairly opaque if you don't know what it's trying to say. http://php.net/manual/en/function.setcookie.php

Upvotes: 4

Related Questions