An Introduction To PHP Sessions
How Do I Use a Session?
Here we will demonstrate a session in its simplest form, that is, setting a session variable on a web page and recalling the value of it on a second page. We will begin by creating a session variable called
foo and we shall assign the value of
bar to it. A session variable looks like this:
We use the PHP super global
$_SESSION to hold it. More on this later. Our first page we will call
page1.php and the code will look as follows.
// begin the session session_start(); // set the value of the session variable 'foo' $_SESSION['foo']='bar'; // echo a little message to say it is done echo 'Setting value of foo';
With that done, we can create
page2.php, which will start a session, then it will echo the value of the session variable
// begin our session session_start(); // echo the session variable echo 'The value of foo is '.$_SESSION['foo'];
Try the above example, we will build on it as we go and discover new things to do with sessions, but first, let’s look at what happened here. On
page2.php we again used session_start(). You must use this on every page you wish to use sessions. In most cases, it will be the first line of code on the page that does anything, following PHP that a session is happening and to load up the session variables, if a session is not already active, PHP will begin a new session upon adding a new variable to
You cannot send ANYTHING to the browser before session_start().
This means no text, not even a newline or a space. There is a method of doing this but more of that later. Let’s change our
page2.php to echo some text before we use session_start().
// output some text to the browser before starting the session echo 'This is a bad thing to do'; // begin our session session_start(); // echo the session variable echo 'The value of foo is '.$_SESSION['foo'];
When you access
page2.php with the above code, it will give you an error that looks something like this:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /html/page2.php:4) in /html/page2.php on line 7 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /html/page2.php:4) in /html/page2.php on line 7 The value of foo is
As you can see, when the script reaches the session_start() on line 7, it gives an error. This is because session_start() sends headers to the browser, as does sending text. These headers may only be sent once.