PHP sessions question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
enchance
Forum Commoner
Posts: 34
Joined: Sat Sep 15, 2007 12:10 pm

PHP sessions question

Post 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
 
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: PHP sessions question

Post 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.
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Re: PHP sessions question

Post 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
}
?>
enchance
Forum Commoner
Posts: 34
Joined: Sat Sep 15, 2007 12:10 pm

Re: PHP sessions question

Post 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:
Post Reply