可能重复:
PHP 已发送标头
当我在运行用户登录脚本后尝试重定向时,会出现此错误。
它试图更改这一行的标题数据:
header("Refresh: 2; url=index.php");
这是完整的login.php脚本。
<?php
session_start();
require_once('init.php');
$username = trim($_POST['username']);
// create a new object
$login = new Auth($_POST, $dbh);
if($login->validateLogin()){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$list = $login->getUserInfo();
$_SESSION['id'] = $list['id'];
$_SESSION['thumb'] = $list['img_thumb'];
echo '<div class="content">';
echo '<h1>Thank you for logging in '.$username.'. Redirecting...</h1>';
echo '</div>';
header("Refresh: 2; url=index.php");
}else{
echo '<div class="content">';
echo '<h1>Sorry but we didn''t recognise those login details, please try again.</h1>';
echo '</div>';
}
require_once('inc/footer.inc.php');
?>
init.php文件调用包含html5 doctype、元标记等的header.php。
如何在用户登录后将其重定向到索引页面,并像往常一样发送标题信息?
来自PHP文档。
请记住,在发送任何实际输出之前,必须调用
header()
,无论是通过普通HTML标记、文件中的空行还是从PHP发送。
如果你想在几秒钟后重定向页面,你需要使用元刷新。
<meta http-equiv="refresh" content="5;URL='http://example.com/'">
只需在任何echo
语句之前移动header()
调用:
<?php
/* ... */
if($login->validateLogin()){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$list = $login->getUserInfo();
$_SESSION['id'] = $list['id'];
$_SESSION['thumb'] = $list['img_thumb'];
header("Refresh: 2; url=index.php"); // Put this *before* any output
echo '<div class="content">';
echo '<h1>Thank you for logging in '.$username.'. Redirecting...</h1>';
echo '</div>';
}else{
echo '<div class="content">';
echo '<h1>Sorry but we didn''t recognise those login details, please try again.</h1>';
echo '</div>';
}
/* ... */
使用echo然后尝试为Location设置标头总是会引发该错误。?有什么比重定向用户更好的方法让用户知道重定向?如果你想显示这样的消息(如果这种方法有效的话,一秒钟都不会显示),你应该使用javascript来更新内容,并使用某种延迟。。。
但也许工作量太大了。如果你在登录后显示欢迎信息,应该就足够了,对吧?:)