简体   繁体   English

为什么这个cookie不起作用?

[英]Why this cookie doesn't work?

My site have a full version and a mobile version. 我的网站有完整版和移动版。 When type the URL, the index.php will detect user's client to direct to full version or mobile version. 键入URL时, index.php将检测用户的客户端以定向到完整版还是移动版。 This works fine. 这很好。 Users from desktop client can also switch to mobile version. 来自桌面客户端的用户也可以切换到移动版本。 But I have trouble for users from mobile client switching to full version. 但是我给从移动客户端切换到完整版本的用户带来了麻烦。 The codes are here: 代码在这里:

// index.php
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('...',substr($useragent,0,4))) {
  $type = 'mobile';
} else {
  $type = 'full';
}
if ($type == 'mobile' and $_COOKIE['switch'] != 'full') {
  header ('Location: m/');
} else {
  include './front.html.php';
}
?>

// m/switch.php  page when user click
<?php
setcookie('switch', 'full', time() + 60);
header('Location: ../');
?>

I have also reversed the order of setcookie and header , but still doesn't work. 我也颠倒了setcookieheader的顺序,但仍然无法正常工作。

Is it possible cookie is forbidden in mobile device? 是否有可能在移动设备中禁止Cookie?

* Update * *更新*

I added a $type = 'mobile'; 我加了一个$type = 'mobile'; before the condition, so that no matter what client, it is assumed to be mobile. 在此条件之前,因此无论是什么客户端,都假定它是可移动的。 Then I used Chrome from my laptop to test, and the cookies are definitely enabled. 然后,我从笔记本电脑上使用了Chrome进行测试,并确定启用了cookie。 It goes to mobile version (ok), but click switch still does not go to full version. 转到移动版本(确定),但单击“ switch仍不能转到完整版本。 So it is problem of the cookie itself. 因此,这是cookie本身的问题。

You need to specify the path of the cookie 您需要指定Cookie的路径

setcookie('switch', 'full', time() + 60, '/');

From the manual we can know 从手册中我们可以知道

http://php.net/manual/en/function.setcookie.php http://php.net/manual/zh/function.setcookie.php

The path on the server in which the cookie will be available on. Cookie在服务器上可用的路径。 If set to '/', the cookie will be available within the entire domain. 如果设置为“ /”,则cookie将在整个域中可用。 If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. 如果设置为“ / foo /”,则该cookie仅在/ foo /目录和域的所有子目录(如/ foo / bar /)中可用。 The default value is the current directory that the cookie is being set in. 默认值为正在设置Cookie的当前目录。

In you example the script switch.php will set the cookie in the path /m/ (default value is the current directory). 在您的示例中,脚本switch.php将在路径/m/设置cookie(默认值为当前目录)。 However your index.php was trying to read cookie form / , thus the redirection will fail. 但是,您的index.php试图读取cookie形式/ ,因此重定向将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM