This is likely one of our most frequently asked questions. Some day I'll actually get around to making a tutorial on it in the PHP_FAQs forum.
From the looks of your script, it appears that you are using cookies to pass the session id. The session id is a random string of letters and numbers that you pass to the client who in turn passes it back to the server with every new page request. When session_start() is called, it outputs a cookie in the HTTP response headers that contains this id. The cookie is stored on the client's computer, and then passed back to the server with each new page request. Because the cookie is output in the HTTP response headers by session_start(), by default, there can be no output before the call to session_start(). Otherwise, the script should produce an error complaining to the effect of "cannot start session, script output already started at line x".
That said, there a few things that you can do to remedy the problem. The first is avoiding cookies to pass around the session id. Most browsers today have cookies disabled by default, which makes cookies a less user-friendly method of perpetuating the session. If you must use cookies, then you must ensure that they are enabled in your browser, this is done by enabling first-party cookies, or session cookies. Then make sure you have no output, whitespace, HTML, or anything else before the call to session_start()... such as //page1.php
<h1><?php session_start();... the <h1> before the call to session_start() should be causing errors in your script like the one I described.
A second method is to embed the session id directly in the URL using query string arguments.
Code:
//page1.php
<h1><?php session_start();
$_SESSION['sess_var'] = "Hello world!";
echo 'The content of $_SESSION[\'sess_var\'] is '
.$_SESSION['sess_var'].'<br />';
?>
<a href="page2.php?sid=<?php echo session_id(); ?>">Next page</a></h1>
This method will pass around the session id using the URL, effectively bypassing cookies.
The last method is the same as the last step, but requires a change to the php.ini configuration file, and that is to give the session.use_trans_id directive a value of 1. This directive will automatically put the session_id in all of the URLs, forms, etc. Personally, I prefer to do it manually with the second method.
The most important thing to take away from all of this is that it is imperative that the session id make the journey from server to client and from client to server with each page request requiring sessions.
For further reference, read the PHP manual entry for sessions:
http://www.php.net/session
HTH!
Regards,
Rich
::::::::::::::::::::::::::::::::::::::::::
The Spicy Peanut Project
http://www.spicypeanut.net
::::::::::::::::::::::::::::::::::::::::::