PHP sessions question

Discussion in 'PHP' started by enchance, Oct 3, 2009.

  1. #1
    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? :confused:

    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:
     
    enchance, Oct 3, 2009 IP
  2. Oli3L

    Oli3L Active Member

    Messages:
    207
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    70
    #2
    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:
     
    Oli3L, Oct 3, 2009 IP
  3. goliath

    goliath Active Member

    Messages:
    308
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    60
    #3
    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.
     
    goliath, Oct 3, 2009 IP