Using PHP Sessions To Store Information

/ PHP / by Paul Robinson / 0 comments
This post was published back on October 6, 2008 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Something that most people starting out learning PHP ask is how do you store information temporary? Well the answer to the that is by using PHP sessions. So here is a quick overview of how to use sessions in PHP.

Sessions are, in a nutshell, a way of temporary storing information in the browser’s memory while a user is browsing your website. If the user leaves your site or the user shuts their browser window, amnesia sets in and it forgets everything, so make sure the info is not important and can be lost without consequence.

Sessions Crash Course

So a simple example could be to welcome a user using their name. Similar to when you are logged in to any of your favorite shopping websites.

You would first need to connect and retrieve the users information, which you would obviously do at login. Then, also at login, using the session_start() function you can start and store information into a unique session. Something like the following would work just fine:

That’s all there is to it. You must start the session using session_start() before anything is outputted to the browser. That includes HTML, text, chickens, elephants, or even aliens… To use the info on another page just restart the session using the session_start() function again, and then echo out the info as you need it.

So there you go. That was a crash course in PHP sessions. If you have any questions drop me a comment and I’ll try my best to answer them.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more