Using PHP Sessions To Store Information
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:
//Database info collection here...
$_SESSION['name'] = $user_name;
//Any more info you want to store. Do not store passwords etc for security reasons...
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.