Reputation: 4132
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. 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.
Is it possible cookie is forbidden in mobile device?
* Update *
I added a $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. It goes to mobile version (ok), but click switch
still does not go to full version. So it is problem of the cookie itself.
Upvotes: 1
Views: 2587
Reputation: 582
You need to specify the path of the cookie
setcookie('switch', 'full', time() + 60, '/');
From the manual we can know
http://php.net/manual/en/function.setcookie.php
The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
In you example the script switch.php
will set the cookie in the path /m/
(default value is the current directory).
However your index.php
was trying to read cookie form /
, thus the redirection will fail.
Upvotes: 1