会话启动PHP错误消息无法发送会话缓存限制器 - 已发送的标头

时间:2016-12-21 19:44:37

标签: php mysql

我使用相当简单的php脚本(login.php)让用户登录受保护的页面。但是,我一直收到这些错误消息

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /var/sites/f/mysite.co.uk/public_html/users/login.php:15) in /var/sites/f/mysite.co.uk/public_html/users/login.php on line 36

Warning: Cannot modify header information - headers already sent by (output started at /var/sites/f/freedomprogramme.co.uk/public_html/users/login.php:15) in /var/sites/f/freedomprogramme.co.uk/public_html/users/login.php on line 39

,页面不会重定向到欢迎页面,该页面位于顶部

<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("Location: login.php");
}
else
{
?>

以下是login.php的内容

<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="" method="post">
<label>Username:</label><input type="text" name="user"><br/>
<label>Password:</label><input type="password" name="pass"><br/>
<input type="submit" value="Login" name="submit"><br/>
<!--New user Register Link -->
<p><a href="register.php">New User Registration!</a></p>
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
//DB Connection
$conn = new mysqli('xxxx', 'yyyy', 'zzzz') or die(mysqli_error());
//Select DB From database
$db = mysqli_select_db($conn, 'yyyy') or die("databse error");
//Selecting database
$query = mysqli_query($conn, "SELECT * FROM userpass WHERE user='".$user." AND pass='".$pass."'");
$numrows = mysqli_num_rows($query);
if($numrows !=0)
{
while($row = mysqli_fetch_assoc($query))
{
$dbusername=$row['user'];
$dbpassword=$row['pass'];
}
if($user == $dbusername && $pass == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
//Redirect Browser
header("Location:welcome.php");
}
}
else
{
echo "Invalid Username or Password!";
}
}
else
{
echo "Required All fields!";
}
}
?>
</body>
</html>

任何帮助表示赞赏。提前致谢

2 个答案:

答案 0 :(得分:1)

你需要移动

<?php if(isset($_POST["submit"])){ ... ... ... } ?>

<!doctype html>之前的页面顶部。

原因是HTTP响应的标头必须始终位于正文之前。但是在您的代码中,正文(HTML)位于发送标题的函数之前(session_start()header()

答案 1 :(得分:1)

&#34;已发送标题&#34;意味着您的PHP脚本已经发送了HTTP标头,因此它现在无法对它们进行修改。

在致电session_start之前,请检查您是否发送了任何内容。更好的是,只需要在PHP文件中首先执行session_start(所以在所有HTML等之前将它放在绝对的开头)。