Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 951
  • Last Modified:

setcookie in php for subdomain does not work

I have localhost server that I accessed using http://abc/ I'm using cookie to authenticate login like the following and it works great

          setcookie("user_id", $cookie_id, $cookie_time, "/","abc");
          setcookie("user_email", $cookie_email, $cookie_time, "/","abc");
          setcookie("user_password", $cookie_password, $cookie_time, "/","abc");

but then I'd like to make the cookie available for other subdomain, as what php.com says,  i added "." in front of the domain like the following. But now i can't even login because the cookie is not written anywhere. I did echo $_COOKIE[user_id] and the value is empty

          setcookie("user_id", $cookie_id, $cookie_time, "/",".abc");
          setcookie("user_email", $cookie_email, $cookie_time, "/",".abc");
          setcookie("user_password", $cookie_password, $cookie_time, "/",".abc");


Any idea?
0
edyonline
Asked:
edyonline
  • 8
  • 6
  • 4
  • +1
2 Solutions
 
nergikCommented:
hello, try to name your localhost as abc.int
instead of just abc.  then you can play with domain cookie .abc.int. and abc.int. you will also need to create a sub1.abc.int in your machine alias. to test that cookie/session works fine with it.
0
 
nergikCommented:
by the way, i dont recommend using cookies to store user passwords,  if you are trying to authenticate a user you can use php sessions to check if logged using $_SESSION array and php will manage the required cookie
0
 
mankowitzCommented:
What is the other subdomain?

When you use http://abc, the entire domain is just "abc", there is no top-level domain or subdomain. Cookies will not be shared between different domains as a security precaution.

So, if you have your localhost set up so that there are two domains "a.abc" and "b.abc", then you can use the second set of code above. Otherwise, you won't be able to transfer your cookies from one domain to another.

If you really want to transfer cookies between domains, you can do it in javascript. See http://en.allexperts.com/q/Javascript-1520/passing-session-cookies-different.htm
0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
edyonlineAuthor Commented:
ow, so cookie only work with domain.ext ? it can't work with just domain?

i don't have specific subdomain as it can be anything.. that's why i put . in front of the domain
0
 
mankowitzCommented:
Right. in your case "abc" has no subdomain or domain or toplevel domain. It's all one thing. You can edit your hosts file to make "a.abc" and "b.abc" or even "www.google.com" point to localhost for testing.

0
 
Ray PaseurCommented:
Here is an example teaching how to set cookies across subdomains.  You can install it, and run it to see the moving parts in action.  See especially lines 35 - 49.  

HTH, ~Ray
<?php // RAY_cookie_example.php

// RECEIVE FORM INPUT AND SET A COOKIE WITH THE NAME AND VALUES FROM THE FORM
// MAN PAGE: http://us.php.net/manual/en/function.setcookie.php
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES

define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )

if (!empty($_POST)) // IF THE FORM HAS BEEN POSTED
{

// TIDY UP THE POST INPUT - CLEAN AND NOT MORE THAN 16 BYTES
   $name = substr(clean_string($_POST["name"]),0,16);
   $data = substr(clean_string($_POST["data"]),0,16);

// BE SURE WE HAVE USEFUL INFORMATION
   if ( ($name == '') || ($data == '') ) die("MISSING INPUT: PLEASE <a href=\"$PHP_SELF\">TRY AGAIN</a>");


// CHOOSE THE COOKIE NAME AND VALUE
   $cookie_name    = $name;
   $cookie_value   = $data;



// ESTABLISH THE COOKIE LIFE - CHOOSE ONE OF THESE FOR THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
   $cookie_expires = 0;

// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
   $cookie_expires = time() + date('Z') + 30 * 60 * 60 * 24;



// ESTABLISH THE COOKIE DOMAIN SCOPE - CHOOSE ONE OF THESE FOR THE COOKIE
// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
   $cookie_path	= '/';

// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
   $x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
   $y = count($x);
   if ($y == 1) // MAYBE 'localhost'?
   {
      $cookie_domain = $x[0];
   } else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
   {
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
      $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
   }



// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
   $cookie_secure    = FALSE;



// HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)
   $cookie_http      = TRUE;



// SET THE COOKIE
   if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
   {
      echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
   }
   else
   {
      echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
   }



// AT THIS POINT, THE COOKIE HAS BEEN SET, BUT IT IS _NOT_ AVAILABLE TO THIS SCRIPT.
// THE COOKIE WILL NOT BE AVAILABLE TO OUR SERVER UNTIL THE NEXT SCRIPT!
// THIS IS BECAUSE THE BROWSER SENDS THE COOKIE TO OUR SCRIPT BEFORE OUR SCRIPT STARTS RUNNING.
// HOWEVER THE $_COOKIE ARRAY IS NOT IMMUTABLE, AND WE CAN ADD INFORMATION TO IT
// IF WE WANT TO USE IT IN THIS SCRIPT.  THIS IS PROBABLY A BAD PROGRAMMING PRACTICE
   echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
   echo '<pre>$_POST CONTAINS ';   var_dump($_POST);   echo "</pre>\n";
   echo "<br/>THE COOKIE HAS BEEN SET WITH THESE VALUES: \n";
   echo "<br/>COOKIE NAME: $cookie_name \n";
   echo "<br/>COOKIE VALUE: $cookie_value \n";
   echo "<br/>COOKIE EXPIRES: $cookie_expires ";
   echo " == " . date('r') . "\n";
   echo "<br/>COOKIE PATH: $cookie_path \n";
   echo "<br/>COOKIE DOMAIN: $cookie_domain \n";
   echo "<br/>COOKIE SECURE: "; var_dump($cookie_secure); echo " \n";
   echo "<br/>COOKIE HTTP: ";   var_dump($cookie_http);   echo " \n";

   echo "<br/>";
   echo "<br/>TO SEE THE COOKIES, IF ANY, <a href=\"{$_SERVER['PHP_SELF']}\">CLICK HERE</a> \n";
   echo "<br/>";
}

// END OF SETTING THE COOKIE
?>


<form method="post">
COOKIE NAME: <input name="name" /><br/>
COOKIE DATA: <input name="data" /><br/>
<input type="submit" />
</form>


<?php
// SHOW THE COOKIE ARRAY, IF ANY
echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";



// A FUNCTION TO FORCE A STRING TO CHARACTERS ONLY
function clean_string($string)
{
   return trim(preg_replace('/[^A-Z0-9_]/i', '', $string));
}
?>

Open in new window

0
 
Ray PaseurCommented:
As to the advice about top-level domains provided here by others, it looks right on to me.  You might want to consider this scenario...

example.com is a domain, and for the purpose of cookies it is as different from example.net as it is from twitter.com.

It follows that abc is different from abc.net and abc.com - you have to think of the rightmost position of the domain name as having the most importance - it is the "tld" field.

FWIW, I do not know if this code would work with something like example.com.au - maybe someone with that kind of URL can test it for us and post back here with the results.

Best regards for the new year, ~Ray
0
 
edyonlineAuthor Commented:
ok back to my original problem, when i set it to 'abc' I can login successfully in abc but when i go to aaa.abc, it asks me to login again.

I don't want to login again in aaa.abc,  so I set the cookie to '.abc' now i can't even login to both abc and aaa.abc

When I echo the $_COOKIE[user_id], it's all empty. What i did wrong?
0
 
mankowitzCommented:
I don't think you can do "abc" by itself as a domain--

You have to do "a.abc" and "b.abc" as the two sites
0
 
Ray PaseurCommented:
"When I echo the $_COOKIE[user_id], it's all empty. What i did wrong?"

You didn't do anything wrong, per se, except misunderstand the way cookies work.  Cookies just do not work that way.  They apply to a domain (the exact definition of "domain" is important here - it is a term of art).  You've got different domains, so the browser will not send the cookie back.  That is 100% normal.

Also, "a.abc" and "b.abc" as the two sites should not be expected to work.  These domain names are as different as "twitter.com" and "google.com" and so there must not be any cookie cross-pollination per the rules of the WWW.
0
 
edyonlineAuthor Commented:
I understand that http://abc/ and http://aaa.abc/ are different.

In my vhost, I setup abc to point to c:\www\ and i setup aaa.abc point to c:\aaa\

both are using the same database and same authentication technique. What I want to accomplish is, i want to login to http://abc/ and when i go to http://aaa.abc/ i'm still logged in. What should I do to accomplish this?





0
 
edyonlineAuthor Commented:
Continuing from my previous post, since i'm using cookie, and initially i did not specify the domain parameter. It works fine when i logged in to http://abc/ but when i go to http://aaa.abc/ i have to log in again.

I google it and found out that i have to specify the domain parameter and add '.' (dot) in front of it to make it readable across subdomain. that's what i did

          setcookie("user_id", $cookie_id, $cookie_time, "/",".abc");
          setcookie("user_email", $cookie_email, $cookie_time, "/",".abc");
          setcookie("user_password", $cookie_password, $cookie_time, "/",".abc");

but now i can't even login to both http://abc/  and http://aaa.abc/

and btw, aaa can be wildcard and can be anything.
0
 
Ray PaseurCommented:
edyonline: It sounds like you are trying to achieve design criteria for something that will not work in the real world.  I'd like to help if I can.  Can you please step back from this problem and describe the application you are developing - explain to us why you think you need a cookie to work in separate domains.  There are solutions to this, but they are advanced, complicated and require highly specialized programming.
0
 
edyonlineAuthor Commented:
So my understanding of setcookie is not right then? about adding the "." into the domain parameter to allow the cookie shared across subdomain within the same domain?

Ok. I have a user management system that allow them to setup a multiple group. The way I set it up now, I assign subdomain for every group. So I use wildcard subdomain and using php translating the subdomain into group_id.

Since you can have multiple groups (subdomain) when you logged in to the main site, if you have access to manage that group_id, then you should not have to login again. That's what I want to accomplish
0
 
Ray PaseurCommented:
Wow, that is an "interesting" design idea.  If I understand this correctly, you may have to set many cookies.  Here is my thinking and to be honest, I am only a little more than 50% sure this is right.

A cookie can cover ONE subdomain.
A cookie can cover ALL subdomains.

But a cookie cannot cover some subdomains and not other subdomains.

So let's say I am allowed to handle subdomain "A" and "B" but not "C" - then I would need some kind of indication in the cookie about what subdomains I am allowed to use.  That sounds complicated if you have a lot of clients and a lot of subdomains.

You might want to consider a design revision along these lines.  Have the cookie apply to ALL subdomains, and have it contain a pointer to the client record in the data base.  In the client record have an indicator of what subdomains are allowable.  Then in each script you can test the HTTP_HOST to see if the subdomain matches.   This is not flawless, since HTTP_HOST comes from the client browser, but it is pretty good.

HTH, ~Ray
0
 
edyonlineAuthor Commented:
No no. It will need to work for ALL subdomain. PHP will handle if the user does not have access to that group. That's why i just want to get this cookie work for all subdomain because my php script is already handling this.
0
 
mankowitzCommented:
I think that you are making this too theoretical -- in real life, your site will have an actual hosted domain in the traditional format of xxx.yyy.zzz. Just set up your server to mimic that as closely as possible.

Let's pretend that your domain is going to be "example.com". Just set up a couple of vhosts with "aaa.example.com" and "bbb.example.com", edit your hosts file so that example.com points to localhost and set your cookies to be ".example.com".
0
 
edyonlineAuthor Commented:
Ok. What you are saying is, the set cookie is only work with domain with TLD and cannot work with just domain. This is real life and not theoritical, this is intranet site where you can access it by just typing http://yourcomputername/ and http://subdomain.yourcomputername/

0
 
edyonlineAuthor Commented:
I decided to override manually and add the .tld on my internal site. It's working good now. So TLD is required
0
 
Ray PaseurCommented:
I guess you did not try the code example I posted for you.  To bad - it would have saved you a lot of time.
0

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

  • 8
  • 6
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now