How to read main cookie from the sub domain with an existing sub domain cookie in PHP?

你。 提交于 2019-11-29 07:22:57

It looks like the gist of your issue is reading a cookie set in domain.com from sub.domain.com.

Add

session.cookie_domain = .domain.com

to your php.ini to make this happen. If you're on a shared hosting enviroment and can't modify your ini file, try having this somewhere in your code:

ini_set("session.cookie_domain", ".domain.com");

You should now be able to access cookies set by domain.com on subdomain.domain.com.

mvladk

There is a $_SERVER ['HTTP_COOKIE'] variable that contains both sub domain and main domain cookie variables with the same name as one large string. In the following simple piece of code the $cookie_variable array will contain both values of specific variables:

if( 'sub.domain.com' == $_SERVER['HTTP_HOST']) {
  $var_name = 'somedata';
  $domains_counter = 0;
  foreach(explode(';', $_SERVER['HTTP_COOKIE']) as $cookie_variable_string) {
    if( false !== strpos($cookie_variable_string, $var_name.'=') ) {
      $cookie_variable[$domains_counter] = urldecode(
          trim(
              substr(
                  $cookie_variable_string, 
                  strpos($cookie_variable_string, $var_name) + strlen($var_name.'=')
              )
          )
      );
      $domains_counter++;
    }
  }
  var_dump($cookie_variable);
}

Here's a function that gets all variables:

public static function get_http_cookie_variables() {
  $domains_counter = [];
  foreach(explode(';', $_SERVER['HTTP_COOKIE']) as $cookie_variable_string) {
    $key_value = explode('=', $cookie_variable_string);
    $cookie_var_name = trim($key_value[0]);
    if(is_null($domains_counter[$cookie_var_name])) {
      $domains_counter[$cookie_var_name] = 0;
    }
    $http_cookie_variables[$cookie_var_name][$domains_counter[$cookie_var_name]] = urldecode(trim($key_value[1]));
    $domains_counter[$cookie_var_name]++;
  }

  return $http_cookie_variables;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!