我在登录屏幕上遇到PHP错误。成功登录后,用户将被重定向到索引页面。在我的本地主机上这很好用,所以我从来没有真正打扰过这个。但是,在我的网络服务器上,用户没有被重定向,我收到以下错误:
Warning: Cannot modify header information - headers already sent by (output started at /home/chicpiq6/public_html/login.php:18) in /home/chicpiq6/public_html/login.php on line 75
从我所看到的,我应该摆脱之前的空白和开启和关闭标签。也许看看我的代码可以帮助你想象这种情况:
<div class="main-wrapper">
<header>
<?php
require('header.php');
?>
</header>
<section class="page-content">
<section class="login-page">
<h3>Login</h3>
<?php
if(!isset($_SESSION['id'])&& !isset($_SESSION['username'])) {
?>
<form method="post" action="" id="login-form">
<input type="text" id="usernamelogin" name="username" placeholder="Username">
<div class="username-error" style="color: red; font-size: 12px;"></div>
<input type="password" id="passwordlogin" name="password" placeholder="Password">
<div class="password-error" style="color: red; font-size: 12px;"></div>
<input type="submit" name="login" id="login" value="Login">
<h4><a href="#">Forgot password?</a></h4>
<h4><a href="register.php">Register</a></h4>
</form>
<?php }
else if (isset($_SESSION['id'])&& isset($_SESSION['username'])) {
?>
<div class="login-loggedin">
<h3>You're already logged in!</h3>
</div>
<?php
}
?>
</section>
</section>
<footer>
<?php
include('footer.php');
?>
</footer>
</div>
<?php
//Variables
$login = $_POST['login'];
//Variables from db to check against the user's input
if(isset($login)) {
$username = mysqli_real_escape_string($database, $_POST['username']);
$password = mysqli_real_escape_string($database, $_POST['password']);
$sql = mysqli_query($database, "SELECT * FROM users WHERE username = '$username'");
$getdata = mysqli_fetch_array($sql);
$dbpassword = $getdata['password'];
$dbusername = $getdata['username'];
$dbid = $getdata['id'];
if(mysqli_num_rows($sql) > 0) {
$hash = $dbpassword;
if (password_verify($password, $hash)) {
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbusername;
header("Location: index.php");
} else {
?>
<script>
$('.password-error').text("Incorrect password");
</script>
<?php
}
}
else {
?>
<script>
$('.password-error').text("<?php echo $username?> doesn't exist");
</script>
<?php
}
}
?>
错误中提到的第18行是<?php require('header.php'); ?>
第75行是header("Location: index.php");
我应该如何在这些标签后删除空格?如您所见,第15行用于从另一个文件中获取标题。
我尝试在第一次要求之前添加ob_start();
并在PHP的最后一部分之后添加ob_flush();
但是没有帮助(或者我把它们放在错误的位置?)。
任何想法如何解决这个问题?非常感谢你的帮助。
答案 0 :(得分:0)
在发送HTTP标头(使用setcookie或标头)之前发送任何内容时会触发此错误消息。在您的情况下,您在header("Location: index.php");
之前已将HTML发送到您的浏览器。
在HTTP标头之前输出内容的其他常见原因是:
意外空格,通常位于文件的开头或结尾,如下所示:
<?php
// Note the space before "<?php"
?>
为避免这种情况,只需忽略关闭?&gt; - 无论如何都不需要。
显式输出,例如调用echo
,printf
,readfile
,passthru
,代码