[英]PHP Redirection Not Working After Cookie is Set
由于我没有收到任何标头设置错误,因此如何解决PHP中的“标头已发送”错误无法解决该问题。 正在设置cookie,问题是链接转到主页('/')。 它似乎不再进入主页,甚至在跟踪日志上也看不到,我看不到正在重新加载spash.php的条目。 它几乎就像从index.php重定向后(输入http:// domain时 )一样,浏览器/服务器将http://domain/splash.php识别为主页。
我有2页,index.php和spash.php。 index.page首先检查经过身份验证的cookie。 如果为false或未找到,则页面重定向到splash.php spash.php,然后设置经过身份验证的cookie并使用带有“ /” href值的锚标记。 但是单击链接按钮后,该页面仅重新加载spash.php。
我在日志的2页上添加了跟踪error_logs,从日志中可以看到,第一次加载时,它会通过index.php页,然后加载spash.php页,但是即使在多次单击链接按钮之后,也不会不再访问index.php页面的日志。
这是我的代码:
的index.php
<?php if(!isset($_COOKIE['authenticated'])){
error_log("This is Index, Redirect to Splash Page");
header("Location: /splash.php" );
die();
exit();
}else{
echo "meron";
}
?>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h1>Hello</h1>
<?php var_dump($_COOKIE); ?>
</body>
</html>
splash.php
<?php setcookie('authenticated', 1, 0, '/');
error_log("This is Splash, set the cookie");
echo $_SERVER['SCRIPT_FILENAME'];
?>
<html>
<head>
<title>Splash Page</title>
</head>
<body>
<a href="/">GO!</a>
</body>
</html>
注意:
加载启动页面后,如果键入[domain] /index.php,则可以看到主页。
此问题仅在主机上发生,在本地尝试过代码,一切正常
如果我从spash.php( GO! )更改链接按钮的href,则它可以正常工作。 但是我需要该值才是领域。
使用header
位置时,之前不应有任何echo
或空格。
确定,我找到了间接解决方案。 我没有使用服务器端代码(PHP)的重定向功能,而是使用了javascript,现在可以正常工作了。
请参阅下面的更新代码:
的index.php
<html>
<head>
<title>Index Page</title>
<script>
document.addEventListener('DOMContentLoaded', onLoad());
function onLoad(){
if(getCookie('astig') == ''){
window.location.href = "/splash.php";
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</head>
<body>
<h1>Hello</h1>
<?php var_dump($_COOKIE); ?>
</body>
spash.php
<html>
<head>
<title>Splash Page</title>
<script>
document.addEventListener('DOMContentLoaded', onLoad());
function onLoad(){
document.cookie = "astig=true;0;path=/";
}
</script>
</head>
<body>
<a href="http://laviel.rocks">GO!</a>
</body>
在托管提供商的支持下获得了解决方案。 他禁用了mod过期缓存。 现在,我可以通过纯服务器端脚本进行重定向了。
只是不确定此选项的总体效果以及哪种方法会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.