Follow me on GitHub

PHP函数setcookie写入重名cookie

测试代码

测试代码

测试代码如上图

执行结果

执行结果

执行结果如上图

setcookie函数介绍

The setcookie() function sends an HTTP cookie to a client.

A cookie is a variable, sent by the server to the browser. A cookie is typically a small text file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too.

The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name “user”, a variable is automatically created called $user, containing the cookie value.

A cookie must be assigned before any other output is sent to the client.

This function returns TRUE on success or FALSE on failure.

W3school

分析:

  1. 同一域(不包括子域)上,cookie重名,则后定义的覆盖之前的;
  2. 非同域,则先写入的先发送

所以

由于通过子域名“l.cuobian.com”访问,所以根域和子域的cookie均发送。至于为什么只显示先接收到(先定义)的cookie值,可能和$_COOKIE读取机制有关,

  • 第一代码块中,同域(不定义则默认为受访域名)名为“order”的cookie 覆盖后显示“latter”;
  • 第二代码块中,名为“domain”的cookie “cuobian.com”先定义先发送,先被接收被显示;
  • 第三代码块中,同域覆盖后等效于只运行后两行,“l.cuobian.com”先定义故被显示。
使用$_SERVER[‘HTTP_COOKIE’] 可以验证,确实接收到了同名不同域的两个cookie值。
通过$_SERVER['HTTP_COOKIE'] 可以验证的执行结果

通过$_SERVER[‘HTTP_COOKIE’] 可以验证的执行结果

还没人围观.

注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。使用'@all ',将会将评论发送给之前所有其它评论者。请务必注意user必须和评论者名相匹配(大小写一致)。


移动设备浏览当前页