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 which is header ("Location: http://localhost/labs/php_sessions/page2.php"); but how can that be? I simplified the markup and made the PHP in bold so it's easier to see: [B]<?php session_start(); if($_POST['pass'] == '123'){ $_SESSION['login'] = true; } else { $_SESSION['login'] = false; } ?>[/B] <html> <head></head> <body> [B]<?php if($_SESSION['login']){ header ("Location: http://localhost/labs/php_sessions/page2.php"); exit(); } else { ?>[/B] <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"> <input name="pass" type="password" /><input name="" type="submit" /> </form> [B]<?php } ?>[/B] </body> </html> Code (markup): And just in case, here's the actual error message 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 HTML:
try this code: <?php ob_start(); 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> <?php ob_flush(); ?> PHP:
The problem is your sequence, the message is very literal. because you have already sent your <HTML> and <HEAD> you can not send any more headers. As soon as a character is sent as content the headers are over. instead of this try this: That will fix it for you.