Today I bring to you, sessions. What they are and how to use them. So lets get started.
What does a session look like? If you were to print_r, wrapped with <pre> tags, it is nothing more than a associative array. Heres an example of one my user management sessions:
'user_data' => Array(
'logged_in' => false,
'username' => false,
'display_name' => false,
'login_time' => false
Now because it is an array, I would access the above session data by writing out $_SESSION['user_data']['logged_in']. $_SESSION is the key variable here. Easy right?
Its that simple, now what would you do with it? Well, like the above shows, you could store user information, or admin information, or the more popular, shopping cart information. Note that all session data is stored SERVER side, and does expire after a while. The expiration time from the time the session data is created, can be changed in php.ini I believe. If you are looking for a more long term approach then I would recommend using cookies to store data on the clients browser.
Remember to start every page with session_start(). This will enable you to access the $_SESSION variable, if it is not on every viewable page, you can not use $_SESSION on that page. If you’re looking to remove a session, simply just call session_destroy(). This will remove the session entirely. If you are looking to remove just on session key, try setting that key to false, removing the value.
Now if you want something more advanced, you can try encrypting session data, or going with a frameworks like Code Igniter. Frameworks like Code Igniter use their own private session data, which is still stored server side, but gives more options to sessions.
I hope this helps.
Learn more here.
Thanks for reading,