如何从具有PHP中现有子域cookie的子域读取主cookie? [英] How to read main cookie from the sub domain with an existing sub domain cookie in PHP?

查看:101
本文介绍了如何从具有PHP中现有子域cookie的子域读取主cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当子域cookie和主域cookie同时存在时,我需要为子域使用主域cookie,因为它具有更高的优先级.

I need to use main domain cookies for my sub domains as with higher priority when both sub and main domain cookies exists.

问题是当我在 sub.domain.com 上并且存在Cookie时

The problem is when I'm on sub.domain.com and there exist cookies for

  • sub.domain.com
  • .domain.com

PHP全局$_COOKIE包含$_COOKIE['data'] == 'sub.domain.com'. 我想检查是否还有一个 .domain.com cookie并使用它.

The PHP global $_COOKIE contains $_COOKIE['data'] == 'sub.domain.com'. I would like to check if there is also a .domain.com cookie and use it.

当我位于具有现有子域cookie的子域中时,如何读取主cookie?

How do I read the main cookie when I'm on a sub domain with an existing sub domain cookie?

推荐答案

有一个$_SERVER ['HTTP_COOKIE']变量,它包含与一个大字符串同名的子域和主域cookie变量.在以下简单的代码段中,$cookie_variable数组将包含特定变量的两个值:

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;
}

这篇关于如何从具有PHP中现有子域cookie的子域读取主cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆