我在这里阅读了很多关于header('location.')
的问题和答案,并尝试根据它调整我的代码,但我似乎无法使其适用于我的登录页面。我得到了常见的错误
警告:无法修改标头信息 - 已在/ Applications / MAMP / htdocs / Curie / src / CUser / CUser中发送的标头(输出从/Applications/MAMP/htdocs/Curie/webroot/nobel_login.php:1开始)第33行的.php
我也知道必须在发送任何实际输出之前调用header(),无论是普通HTML标记,文件中的空行还是PHP。我该如何编写此代码(请参阅下文)以使其有效?提前感谢您的意见和建议。
<?php
/**
* A class for handeling login
*
*/
class CUser extends CDatabase {
/**
* Members
*
*/
private $database;
/**
* Initiate child and parent constructor
*
*/
public function __construct($database) {
parent::__construct($database);
}
/**
* Check if user and password is okey and reload page
*
*/
private function Login() {
if(isset($_POST['login'])) {
$sql = "SELECT acronym, name FROM USER WHERE acronym = ? AND password = md5(concat(?, salt))";
$params = array(strip_tags($_POST['acronym']), strip_tags($_POST['password']));
$res = $this->ExecuteSelectQueryAndFetchAll($sql, $params);
if(isset($res[0])) {
$_SESSION['user'] = $res[0];
}
// Den ska skrivas ut innan html skrivs ut.
header('Location: nobel_login.php');
}
// Logga ut användare / Logout the user
if(isset($_POST['logout'])) {
unset($_SESSION['user']);
header('Location: nobel_login.php');
}
}
/**
* Verify if user is logged in or not and return message
*
*/
private function IsAuthenticated($acronym) {
if($acronym) {
$acronym = $_SESSION['user']->acronym;
$name = $_SESSION['user']->name;
$output = "Du är inloggad som: {$acronym} ({$name})";
}
else {
$output = "Du är för närvarande inte inloggad.";
}
return $output;
}
/**
* Create login form
*
*/
private function LoginForm($acronym) {
$form = "<form method='post'><fieldset><legend><br></legend>";
$form .= "<p><em>Du kan logga in med vinga:vinga eller pippi:pippi</em></p>";
$form .= "<p><label>Användare:</label><br><input type='text' name='acronym' value='pippi'></p>";
$form .= "<p><label>Lösenord:</label><br><input type='password' name='password' value='pippi'></p>";
$form .= "<p><input type='submit' name='login' value='Login'> ";
$form .= "<input type='submit' name='logout' value='Logout'></p>";
$form .= "<p><b>{$this->IsAuthenticated($acronym)}</b></p>";
$form .= "</fieldset></form>";
return $form;
}
/**
* Sum it all up and create HTML output
*
*/
public function UserLogin() {
// Get parameters
$acronym = isset($_SESSION['user']) ? true : false;
// Create HTML output based on parameters
$html = $this->Login();
$html .= $this->LoginForm($acronym);
return $html;
}
}