Home  >  Article  >  Backend Development  >  PHP 5.5.9版本中COOKIE的奇怪现象

PHP 5.5.9版本中COOKIE的奇怪现象

WBOY
WBOYOriginal
2016-06-06 20:24:191274browse

我在localhost下建了四个文件

<code>/1.php
/a/1.php
/test/1.php
/test/a/1.php</code>

文件中的代码都是一样的

<code><?php setcookie( __DIR__ ,__DIR__ );
var_dump($_COOKIE);</code></code>

我本以为,所有页面打开后,反复刷新,直到所有的cookie都设置完,结果应该是一样的。
但实际上不是

<code>/1.php            array(1) { ["/var/www/html"]=> string(13) "/var/www/html" } 


/a/1.php            array(2) { ["/var/www/html/a"]=> string(15) "/var/www/html/a" ["/var/www/html"]=> string(13) "/var/www/html" } 


/test/1.php       array(2) { ["/var/www/html/test"]=> string(18) "/var/www/html/test" ["/var/www/html"]=> string(13) "/var/www/html" } 


/test/a/1.php      array(3) { ["/var/www/html/test/a"]=> string(20) "/var/www/html/test/a" ["/var/www/html/test"]=> string(18) "/var/www/html/test" ["/var/www/html"]=> string(13) "/var/www/html" } </code>

明显看出 php的$__COOKIE 获取的cookie是文件所在层级到根目录,这个范围中设置的cookie。而更深层的文件设置的cookie和平级但不同目录的文件设置的cookie,是获取不到的。
我想问
假设 /test/1.php 文件要获取/test/a/1.php 文件设置的cookie,怎么做到呢?
这种现象出现的原理是什么呢?

回复内容:

我在localhost下建了四个文件

<code>/1.php
/a/1.php
/test/1.php
/test/a/1.php</code>

文件中的代码都是一样的

<code><?php setcookie( __DIR__ ,__DIR__ );
var_dump($_COOKIE);</code></code>

我本以为,所有页面打开后,反复刷新,直到所有的cookie都设置完,结果应该是一样的。
但实际上不是

<code>/1.php            array(1) { ["/var/www/html"]=> string(13) "/var/www/html" } 


/a/1.php            array(2) { ["/var/www/html/a"]=> string(15) "/var/www/html/a" ["/var/www/html"]=> string(13) "/var/www/html" } 


/test/1.php       array(2) { ["/var/www/html/test"]=> string(18) "/var/www/html/test" ["/var/www/html"]=> string(13) "/var/www/html" } 


/test/a/1.php      array(3) { ["/var/www/html/test/a"]=> string(20) "/var/www/html/test/a" ["/var/www/html/test"]=> string(18) "/var/www/html/test" ["/var/www/html"]=> string(13) "/var/www/html" } </code>

明显看出 php的$__COOKIE 获取的cookie是文件所在层级到根目录,这个范围中设置的cookie。而更深层的文件设置的cookie和平级但不同目录的文件设置的cookie,是获取不到的。
我想问
假设 /test/1.php 文件要获取/test/a/1.php 文件设置的cookie,怎么做到呢?
这种现象出现的原理是什么呢?

你去看下setcookie的文档。
setcookie的第三个参数path可以定义cookie生效的目录。 把path设置成/, 就说明cookie可以在域名下公用。

这种现象防止cookie变量冲突,也更安全。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn