Forum Moderators: coopster

Message Too Old, No Replies

session variables

session_start generates error

         

opiston

2:59 am on Aug 3, 2005 (gmt 0)

10+ Year Member



Hi all,
I just started learning how to use session variables. I am confused on how to use session_start() and how the session variables are carried over to other pages.

This is the code that I found at

http://us2.php.net/function.session-start

page1.php:

<?php
// page1.php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
echo '<br /><a href="page2.php">page 2</a>';
?>

page2.php

<?php
// page2.php
session_start();

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
?>

When I run this code, I get an error says:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/csmajs/lina/.html/test/page2.php:1) in /home/csmajs/lina/.html/test/page2.php on line 3

My first question is, why is the code giving an error? is it because session_start() was used twice?
My second question is, do I have to add session_start() on every page that I want to use $_SESSION['blah'] at?

Any help would be appreciated
Thanks
Opiston

chrisjoha

6:28 am on Aug 3, 2005 (gmt 0)

10+ Year Member



It looks like page2.php is sending output before the session is started. Make sure you trim off any whitespace and other ouput (stuff outside <?php) before starting the session. As an answer to your other question - yes, you must start the session on every page you want to use the _SESSION variable.

opiston

7:41 am on Aug 3, 2005 (gmt 0)

10+ Year Member



Hi chrisjoha,
I did have a whitespace before <?php. I delete the whitespace and there wasn't anymore warning.

This problem would take me forever to figure out if you didn't help.
Thank you for your help.
Opiston