PHP - Using Sessions

From Global Programming Syntax

Jump to: navigation, search

Sometimes when designing a website you would like pages to swap variables without the user clicking a link or posting a form. Alternatively cookies could be used for the same thing but more than 4 cookies for the one website would be too many and could give you a bad reputation. So to solve the problem of having dozens of cookies, it is possible to have just use what is called "Sessions" which allows "global server side variables" to be passed between pages without the user knowing about it. When sessions are used, there are two ways to identify users between each other. One is the automated system of sending a single cookie for the entire session and the other option is to place the user id in the url bar. Placing the user id in the url bar is the most compatible option because if a user has cookies disabled then the user id can still be retrieved from the url if it is there.

The basics

To use sessions, you always need to place into the very top of your php file the following code:

<?php session_start();

However do not place any browser output before the session_start() function. If you do an error will be reported back. Also some text editors will always force html output on the first line but that is usually rare. If you suspect that your php editor is adding some hidden text before the php opening tag on line one then simple solution is to open the same file in notepad and delete anything before the php opening tag. Note that some ascii characters are blank so click to the right of the < symbol and press backspace a few times. Then type back in the < symbol. Then save and test and if there is no longer an error then it means that your editor does add some hidden text at the beginning of each file.

Next step is how do we use the sessions. It is fairly straight forward and is as simple as using variables. Basically sessions have an array called $_SESSION and anything placed into this array/variable can be read by php on any page and by anyone who hacks the session. So below is an example of the comparison of variables an sessions.

//using a variable
$variable='some text';
 
//using a session
$_SESSION['variable']='some text';

With the above code in mind, every page that uses sessions must have the session_start() function at the beginning. Below is an example of a page using every essential part of sessions:

<?php session_start();
$_SESSION['myname']='cwarn23';
echo '<a href="page2.php">Page 2 with cookies enabled</a><br>';
echo '<a href="page2.php?'.SID.'">Page 2 without cookies</a>';
?>
 
Now page 2
<?php session_start();
echo 'The value was: ';
echo $_SESSION['myname'];
?>
Personal tools
languages
page stats
Toolbox