Results 1 to 7 of 7

Thread: $_SESSION errors

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2009
    Posts
    156

    $_SESSION errors

    I'm trying to use $_SESSION for the first time.

    When testing my script in EasyPHP everything works OK but when I upload I keep getting this message...

    Cannot send session cookie - headers already sent

    This is how I've used the code

    page 1
    PHP Code:
     session_start();
    // defalt testing login
    $username "myname";
    $password "mypassword"
    $_SESSION['username']= $username;
    $_SESSION['password']= $password
    page 2
    PHP Code:

    $username 
    $_SESSION['username'];
    $password $_SESSION['password'];

    echo 
    $password;
    echo 
    $username

  2. #2
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: $_SESSION errors

    Ensure nothing is being output to the browser before session_start();. If something is output, you will get the error you've mentioned.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Mar 2009
    Posts
    156

    Re: $_SESSION errors

    how should I ensure nothing is being output to the browser?

    by using session_destroy()?

  4. #4
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: $_SESSION errors

    You should be able to tell if your code is outputting something to the browser.

    For example
    PHP Code:
    //breaks
    <?php
    echo "test";
    session_start();
    ?>

    //also breaks
    <html>
    <?php
    session_start
    ();
    ?>

    //Doesn't break
    <?php
    session_start
    ();
    ?>
    <html>

  5. #5
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: $_SESSION errors

    You also need to use session_start() at the top of every page in which you access session vars. So page 2 needs to be:
    Code:
    session_start();
    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
    
    echo $password;
    echo $username;
    In addition to kfcSmitty's examples, whitespace also counts as "output." So if you have a blank line prior to your <?php session_start(), get rid of that as well.

  6. #6
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

  7. #7
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: $_SESSION errors

    Also, because PHP does not support Unicode, encoding in UTF-8 with a byte-order-mark (BOM) will cause this problem because the BOM is considered output.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width