-4

so I am attempting to use sessions... I get this error:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home1/####/public_html/####/index.php:3) in /home1/####/public_html/####/index.php on line 4

index.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
    session_start();
    echo $_SESSION['logged_in'];
    echo $_SESSION['logged_user'];
?>
<head>

Any Idea why this might be happening?

Night
  • 731
  • 5
  • 14

2 Answers2

6

Once you output HTML, or any content, PHP can no longer send the headers required to use sessions (i.e. set cookies). You must call session_start() before any output is generated from your script:

<?php
    session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
    echo $_SESSION['logged_in'];
    echo $_SESSION['logged_user'];
?>
<head>
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 2
    please mark as duplicate rather than answering, you dont need the rep points ;-) –  Jan 28 '14 at 19:49
1

You cannot send headers (like session_start) after you already output content.

qwertynl
  • 3,912
  • 1
  • 21
  • 43