这是我的用户登录页面。在用户输入登录详细信息后,我想存储cookie文件并将用户引导到主页。然而,我一直得到这个错误,我已经尝试了所有可能的方法来解决它,我已经阅读了其他问题张贴在这里,但没有解决我的问题…我错过什么了吗?会是什么呢?
<?php //<--- line 4
错误信息:
Warning: Cannot modify header information - headers already sent by (output started at /www/99k.org/p/h/o/phoneclassmate/htdocs/login.php:4) in /www/99k.org/p/h/o/phoneclassmate/htdocs/login.php on line 6
问题是您试图在 HTML代码之后发送HTTP标头(位置:)。
你应该重构你的代码来避免这种情况;或者作为一种hack,您可以使用输出缓冲来解决这个问题,这将允许您在开始输出HTML内容后修改HTTP头。在我看来,这不是一个处理问题的好方法,但无论如何都很好;看到http://ca.php.net/manual/en/function.header.php refsect1-function.header-notes
您需要将if语句块括起来,如下所示:
if($_POST['submit']) {
$hour = time() + 3600;
setcookie('username', $_POST['username'], $hour,'/');
setcookie('password', $_POST['pass'], $hour,'/');
header("Location: tutorhomepage.php");
}
此外,您需要将连接等部分移动到上述部分之后。
<?php
if($_POST['submit']){
$hour = time() + 3600;
setcookie('username', $_POST['username'], $hour,'/');
setcookie('password', $_POST['pass'], $hour,'/');
header("Location: tutorhomepage.php");
}
//------ server and mysql connection
$connection = mysql_connect('mywebsite', 'username', 'password') or die('Unable to connect');
mysql_select_db('myDB') or die('unbable to select DB');
//------log in cookie check
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
$pass = $_COOKIE['password'];
$check = mysql_query("SELECT * FROM tutors WHERE username = '$username'") or die(mysql_error());
while ($info = mysql_fetch_row($check)) {
if ($pass != $info[1]) {
} else {
header("Location: /tutorhomepage.php");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body><?php
//------- if form is submitted
if (isset($_POST['submit'])) {
// check if the user enetered login details
if (!$_POST['username'] | !$_POST['pass']) {
die('You must enter the required data.');
}
// and so on