Page 1 of 1

PHP sessions question

Posted: Sat Oct 03, 2009 10:59 am
by enchance
I've only started to use php sessions but I keep getting an error. Can someone tell me why my code below doesn't work? Firefox says my problem is in line 21 (line 18 here) which is header ("Location: http://localhost/labs/php_sessions/page2.php"); but how can that be? :(

I simplified the markup so it's easier to see:

Code: Select all

 
<?php
session_start();
if($_POST['pass'] == '123'){
    $_SESSION['login'] = true;  
}
else {
    $_SESSION['login'] = false;
}
?>
 
<html>
<head></head>
 
<body>
<?php
if($_SESSION['login']){
    header ("Location: http://localhost/labs/php_sessions/page2.php");
    exit();
}
else {
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input name="pass" type="password" /><input name="" type="submit" />
</form>
<?php
}
?>
</body>
 
</html>
 

And just in case, here's the actual error message

Code: Select all

 
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\labs\php_sessions\index.php:19) in D:\xampp\htdocs\labs\php_sessions\index.php on line 21
 

Re: PHP sessions question

Posted: Sat Oct 03, 2009 11:38 am
by jackpf
Have you even googled this error message? It's possibly the most frequently encountered error message like....EVER.

Headers before output. Or use output buffering.

Re: PHP sessions question

Posted: Sat Oct 03, 2009 11:43 am
by JKM

Code: Select all

<?php
if($_SESSION['login']){
    header ("Location: http://localhost/labs/php_sessions/page2.php");
    exit();
}
else {?><!DOCTYPE html PUBLIC "-//W3C//Dli XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/Dli/xhtml1-transitional.dli">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>login</title>
</head>
 
<body>
<form action="" method="post">
    <input name="pass" type="password" /><input name="" type="submit" />
</form>
</body> 
</html>
<?php
}
?>

Re: PHP sessions question

Posted: Sat Oct 03, 2009 12:07 pm
by enchance
Thanks , JKM. I see where you're getting at. I studied it and now I know where I went wrong. You can't use header() when HTML has already been generated since the headers have already been sent. Stupid me. :mrgreen: