如何使用PHP中的现有子域cookie从子域读取主cookie [英] How to read main cookie from the sub domain with an existing sub domain cookie in PHP
问题描述
我需要为子网域使用主网域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 ,并且
- 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 are also .domain.com cookie and use it.
如何
推荐答案
有$ _SERVER [ 'HTTP_COOKIE']变量,其中包含与一个大字符串同名的子域和主域cookie变量。在下一个简单代码中,$ cookie_variable数组将包含特定变量的两个值。
There is $_SERVER ['HTTP_COOKIE'] variable that contains both sub domain and main domain cookie variables with the same name as one large string. In next simple code $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);
}
创建的函数可获取所有变量:
Created function that gets all variables:
public static function get_http_cookie_variables()
{
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屋!