Paul Williams
Paul Williams

Reputation: 1598

Setting a cookie for two domains

I'm trying to set two cookies for the same site. (Except one is a HTTP and one is a HTTPS site.)

 $cookie_domain_http = parse_url(HTTP_SERVER);
 $cookie_domain_https = parse_url(HTTPS_SERVER);

Assuming that HTTP_SERVER contains http://www.somesite.com and that HTTPS_SERVER contains https://ssl1.otherdomain.com, I'm using the following.

   setcookie("referrer_key",
     $_GET['referrer'],
     time() + 60*60*24*365,
     $cookie_domain_http['path'], 
     $cookie_domain_http['host']); // Set the cookie for the non-HTTPS version.

if(ENABLE_SSL == "true") {
   setcookie("referrer_key",
     $_GET['referrer'], 
     time() + 60*60*24*365, 
     $cookie_domain_https['path'], 
     $cookie_domain_https['host']); // Set the cookie for HTTPs version.
}

Now the first setcookie is setting the session cookie correctly. However, the second line isn't causing it to display.

How can I use this code, specifically PHP to do this.

Upvotes: 0

Views: 3272

Answers (2)

andrewsi
andrewsi

Reputation: 10732

You can only set a cookie in one domain, the one your code is running on. The closest you can get is setting to somesite.com, in which case it will be sent to all subdomains of somesite.com

You can't set cookies on both somesite.com and othersite.com in the same piece of code.

Otherwise, there's nothing to stop you from adding cookies for arbitrary domains.

Upvotes: 3

Bryan
Bryan

Reputation: 6752

http://php.net/manual/en/function.setcookie.php

There's one more parameter at the end, that you can use to specify whether or not the cookie is secure.

if (ENABLE_SSL == "true") 
  setcookie("referrer_key", 
  $_GET['referrer'], 
  time() + 60*60*24*365, 
  $cookie_domain_https['path'], 
  '.somesite.com', // Parse out the base domain, and put it here with the leading "."
  true); //this is the parameter to set specify a secure cookie

Upvotes: 2

Related Questions