How to Use Session Variables in PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

We continue from the previous tutorial.   Here is demo.

4. Now suppose we add a link on the confirmation page to go back to the previous index.php page …

add link back

5.   When we click on that link, we get back the index.php page.  But the input box is empty, suppose we want to persist the value entered so that whatever the user enter is still in the input box for editing.

6.  We need to add the value to a session variable so that it persists across pages.  We call session_start() at the top of the confirmation.php page to use sessions and save to a session variable we call “greeting”…

save session variable

Note that we don’t have to escape when we save to session.  It is preferable to escape right at the time of output to HTML.

7.  Now in the index.php, we can retrieve the session variable and apply htmlspecialchars right before we echo it out…

retrieve session variable

retrieve session variable

Note we had to use session_start() at the top of page here too.

So when we click link back to index.php, we see our entered value …

output

output

So far in our example, we have assumed that your PHP server has magic_quotes turned off.  Whether on or off, the results should be the same as long as there are no quotes (single or double quotes) in the user entry.

In the next tutorial, we learn how to handle magic quotes in PHP.