-
$_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;
-
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.
-
Re: $_SESSION errors
how should I ensure nothing is being output to the browser?
by using session_destroy()?
-
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>
-
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.
-
Re: $_SESSION errors
-
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.