As cookies are on the user's computer they are insecure and unreliable.  It is also slow for the server to have to ask for and receive the data every time a page is loaded.  Instead PHP can use session variables to save data.  These are like cookies but they are stored on the server.  They are secure as long as the server is properly configured.

Create a page called phpsessionsave.php and put this as the first code in the PHP block at the top:


Save, upload and try and the page should be blank.  The first line has started a session and the next one saves some data.  You should always start a session before doing anything else on a page (definitely before any HTML).  It may not cause problems if you use it elsewhere but it can.  It is only the session_start line which should go first all other lines (storing and retrieving data) can go anywhere on the page.

To read the data back create a page called phpsessionread.php and put a session_start() at the top.  Then in the PHP block just under the h1 put this:

echo "<p>$name</p>";

Try that page and you should see fred.

To delete that data you unset the index.  Save phpsessionread.php as phpsessiondelete.php and replace the two lines of PHP with this one:


Save phpsessiondelete.php as phpsessiondestroy.php and replace the deletion line with this:


Try all four session pages in various orders to be sure you understand what each one does.

Your PHP template

Add session_start(); as the first line of PHP code in your template because you will end up using sessions a lot.