Wednesday, 23 November 2016

session - Warning: Cannot modify header information - headers already sent (PHP)

My issue is somewhat similar to the following post..



PHP error: Cannot modify header information – headers already sent



But in my case I chose to start the session once I determine there is no validation errors from the login form and the user's login info matches that of the database. Here is the following code:



Login page (before any html)




session_name('username');
session_name('ip');
session_name('start');
session_start();


Login.php snippet (in the body of html)



         } else {

$user = $_POST['username'];
$userpass = md5($_POST['password']);
$login_results = statement("select username, password from `$admin` where username='$user' and password='$userpass'");

if (mysql_num_rows($login_results)!= 1) {
$errmsg = "Login failed: Username or password not on file";
}else {

$_SESSION['username'] = "$user";
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];

header("Location: index.php");
}
}
}

}


if you look at the else block of the code above i'm verifying the login and if its good I want to assign the sessions variables and go to my index page. Which has this code at the very beginning:




 //Session Timeout Script -- used to determine the amount of time the user has been idle.  If it the user has been idle for longer then the session time, log the user out.
//Secondary to the Timeout Script, the username and ip address is checked for validility and if either fails redirect the user to the login page.
session_cache_expire( 20 );
session_start();

$inactive = 1200;

if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){

header("Location: logout.php");
}
}

$_SESSION['start'] = time();

$newip = $_SERVER['REMOTE_ADDR'];
if (!isset($_SESSION['username']) || empty($_SESSION['username']) || $newip!= $_SESSION['ip']) {
header('Location: login.php');
}



Now reading through the question from that previous author, it was mentioned that header() should be the first thing to execute in the code thats sending the redirect, which in my case is login.php. And doing that allows me to login, but when I log out i'm destroying all my sessions and and using the header() to send me back to the login page. Which will in turn make the login page redirect back to the index page because its the first line of code read. Is there a way to avoid this? so I wouldn't need to repeat some of my code logic I already have in place at the top of login.php?



Andre

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...