I´ve read many of the questions and answers here regarding header('location.')
and tried th adjust my code below according to it, but I can't seem to make it work for my login page. I get the common error
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/Curie/webroot/nobel_login.php:1) in /Applications/MAMP/htdocs/Curie/src/CUser/CUser.php on line 33
I also know that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. How shall I write this code (pls see below) to make it work? Thank you in advance for input and advice.
<?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;
}
}