【发布时间】:2014-08-27 02:01:15
【问题描述】:
在我的网站上,我实现了一个基于 php 设置 cookie 的样式切换器。如果用户单击一个链接,则会设置一个 cookie,并基于该 cookie 在页面的 head 部分引用某个 CSS 文件。这适用于 Mac OS 和 Windows 上的所有浏览器,但 Google Chrome 除外。
这就像没有(总是)设置 cookie,或者如果提供了页面的缓存版本。不过,我无法指出确切的问题,所以我真的希望这里有人能指出我正确的方向!
切换链接如下所示:
<a href="http://www.mywebsite.nl/assets/templates/scripts/styleswitcher.php?SETSTYLE=0">Switch to high contrast</a>
当点击链接并改变样式时,它会变为以下(再次点击时再次返回):
<a href="http://www.mywebsite.nl/assets/templates/scripts/styleswitcher.php?SETSTYLE=1">Switch to normal contrast</a>
这些链接是由这段代码在页面上生成的:
<?php
if(isset($_COOKIE['STYLE'])) {
if ($_COOKIE['STYLE'] == 0) {
$output = "<a href='assets/templates/scripts/styleswitcher.php?SETSTYLE=1'>Switch to normal contrast</a>";
} else {
$output = "<a href='assets/templates/scripts/styleswitcher.php?SETSTYLE=0'>Switch to high contrast</a>";
}
} else {
$output = "<a href='assets/templates/scripts/styleswitcher.php?SETSTYLE=0'>Switch to high contrast</a>";
}
return $output;
?>
链接指向的文件 styleswitcher.php:
<?php
// SET COOKIE FOR 1 YEAR
if(isset($_GET["SETSTYLE"])){
if(setcookie("testcookie",true)){
setcookie("STYLE",$_GET["SETSTYLE"],time()+31622400,"/");
$_COOKIE["STYLE"] = $_GET["SETSTYLE"];
}else{
$_SESSION["STYLE"]=$_GET["SETSTYLE"];
}
} else {
}
// RETURN TO CALLER PAGE
header("Location: ".$_SERVER["HTTP_REFERER"]);
?>
这段代码在页面头部打印了正确的css文件:
<?php
if(isset($_COOKIE['STYLE'])) {
if ($_COOKIE['STYLE'] == 0) {
$output = '<link href="assets/templates/styles/highcontrast.css" rel="stylesheet" type="text/css" />';
} else {
$output = '<link href="assets/templates/styles/screen.css" rel="stylesheet" type="text/css" />';
}
} else {
$output = '<link href="assets/templates/styles/screen.css" rel="stylesheet" type="text/css" />';
}
return $output;
?>
在 Chrome 中单击链接时,css 不会更改。大多数时候,我在开发人员工具中根本看不到 cookie 被设置,但有时它确实设置了一次,但再次单击链接时不再更改,从而显示错误的 css。有谁知道可能导致 Chrome 出现问题的原因是什么?
最后一件事,在 .htaccess 文件中,我还有一些代码来控制缓存。会不会跟这有关系?
.htaccess 文件
#ExpiresActive On
#ExpiresByType image/gif A2592000
#ExpiresByType image/jpeg A2592000
#ExpiresByType image/png A2592000
BrowserMatch "MSIE" brokenvary=1
BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
BrowserMatch "Opera" !brokenvary
SetEnvIf brokenvary 1 force-no-vary
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
#ExpiresByType text/css "access 1 month"
#ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
# ExpiresDefault "access 1 month"
</IfModule>
## DEFLATE ##
<ifModule mod_deflate.c>
<filesMatch "\.(js|css|html|php|svg)$">
SetOutputFilter DEFLATE
</filesMatch>
</ifModule>
我已经禁用了 css 和 html 以及默认值的 ExpiresByType 规则,但无济于事。
非常感谢您的帮助! - 米歇尔
【问题讨论】:
标签: php html css google-chrome cookies