PHP-设置Cookie并重定向 [英] PHP - Set cookie and redirect
问题描述
我正在尝试设置Cookie并重定向.在PHP 5.3.3-7 + squeeze19和Suhosin-Patch(cli)(内置:2014年2月17日10:10:23)和Apache/2.2.16(Debian)中使用Debian GNU/Linux 6.0(64位)和PHP 5.3.3-7 + squeeze19.
I am trying to set a cookie and redirect. Using Debian GNU/Linux 6.0 (64 bit) with PHP 5.3.3-7+squeeze19 with Suhosin-Patch (cli) (built: Feb 17 2014 10:10:23) and Apache/2.2.16 (Debian).
出于某些原因,它起作用:
For some reason this works:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
但这不是:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location: http://www.example.com");
exit;
?>
即使在加载多个页面之后.我尝试将错误报告添加到代码顶部,但是在加载页面或Apache日志(/var/log/apache2/error.log)时都看不到任何错误:
Even after several page loads. I've tried adding error reporting to the top of my code, but I don't see any errors when I load the page nor in the Apache log (/var/log/apache2/error.log):
error_reporting(E_ALL);ini_set('display_errors','1');
由于某种原因,无论何时我重定向,即使使用如下所示的javascript,也不会添加cookie.
For some reason whenever I redirect, even using javascript as below, a cookie will not add.
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="1;url=http://www.example.com">
<script type="text/javascript">
window.location.href = "http://www.example.com"
</script>
<title>Page Redirection</title>
</head>
<body>
If you are not redirected, follow <a href='http://www.example.com'>this link</a>!
</body>
</html>
为什么第一个示例有效,而其他示例无效?
Why does the first example work but not the others?
推荐答案
我也变得很奇怪,但是使用了js重定向.在XP上使用Chrome浏览器进行测试.
I was also getting this weirdness but with js redirect. Testing with chrome browser on xp.
我解决的方法是使用document.cookie =
The way I solved it was to do the cookie setting with injected js using document.cookie =
?>
<script type="text/javascript">
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
setCookie("foo","<?php echo $bar; ?>",30);
window.location = "<?php echo $destination_page; ?>.php";
</script>
<?php
然后问题消失了.
感觉重定向由于某种原因导致php setcookie失败...
It felt like the redirect was causing the php setcookie to fail for some reason...
这篇关于PHP-设置Cookie并重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!