Sessions In PHP – Very Simple Examples

Welcome to a tutorial on how to use sessions in PHP. So you have heard of this user session thing, and trying to figure out how it works?

  • Call session_start() to start the session.
  • We can then use the $_SESSION superglobal just like a “regular variable” to store and retrieve data from the session. For example:
    • $_SESSION['color'] = "Red";
    • echo $_SESSION['color'];
  • Lastly, use session_destroy() to end the session.

That covers the basics, but just how the session work? Let us walk through more examples and details in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Sessions Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

PRELUDE – HOW COOKIES WORK

Cookies In PHP – Very Simple Examples

Before going any further, it is highly recommended that you have a good grasp of how cookies work in PHP first. They are a fundamental part of sessions, and you will struggle to understand sessions without prior knowledge of cookies.

 

 

PHP SESSIONS

All right, let us now get into the examples and details of how sessions work in PHP.

 

1) START SESSION

1-start.php
<?php
// (A) START SESSION
session_start();
 
// (B) CURRENT SESSION ID
echo session_id();

Starting a session in PHP is as simple as calling session_start(). But just what is the session ID, and what is happening behind the scenes? This can be quite brutal, so follow along:

  • PHP first generates a random and unique session ID.
  • Then sends a PHPSESSID = RANDOMID cookie to the browser.
  • A session file sess_RANDOMID is also created in the temporary folder, as defined in session.save_path in php.ini.

So simply put – The session ID in the cookie will tie back to the temporary session file on the server.

 

 

2) SAVING VARIABLES INTO THE SESSION

2-set.php
<?php
// (A) START SESSION
session_start();
 
// (B) THESE WILL SAVE INTO THE TEMP SESSION FILE
$_SESSION['Color'] = "Red";
$_SESSION['Food'] = "Burger";

What is the big deal with the temporary session file on the server then? Introducing, the $_SESSION superglobal. Everything that we assign to it will be saved inside the temporary session file.

 

3) RESUMING SESSIONS

3-resume.php
<?php
// (A) START SESSION
session_start();
 
// (B) SESSION VAR DUMP
// COLOR => RED
// FOOD => BURGER
var_dump($_SESSION);

Some of you sharp code ninjas should have already figured out the session mechanics at this stage. For you guys who don’t, on subsequent visits to the websites:

  • The browser will send the PHPSESSID cookie back to the server.
  • session_start() will pick up this cookie, load, and restore $_SESSION from the sess_RANDOMID file.

In other words, we can save whatever temporary variables in $_SESSION safely. The user can navigate to any page, and the temporary variables will still be available in $_SESSION.

 

 

4) STORING ARRAYS

4-array.php
<?php
// (A) SESSION START
session_start();
 
// (B) $_SESSION CAN STORE STRINGS
$_SESSION['Color'] = "Red";
 
// (C) ARRAYS
$_SESSION['Fruits'] = ["Apple", "Banana", "Cherry"];
 
// (D) EVEN OBJECTS!
class Foo {}
$_SESSION['Obj'] = new Foo();

Just a quick example here, the data in the temporary session file is serialized. Meaning, we can pretty much store anything in $_SESSION – Strings, numbers, boolean, arrays, even objects!

 

5) END SESSION

5-close.php
<?php
// (A) CURRENT SESSION
session_start();
 
// (B) END SESSION
session_destroy();

Finally, just use session_destroy() to close the session. Take note, some people may prefer to use unset($_SESSION) instead. Nothing wrong with that, but take note of the difference –

  • session_destroy() will close the session entirely. Delete the session cookie and temporary session file on the server.
  • unset($_SESSION) will not end the session, but empty out all current session variables.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COOKIES VS SESSIONS

For you guys who are lost still with cookies and sessions –

  • Cookies are small pieces of data that are saved in the user’s device.
  • Sessions hold temporary data that are saved on the server.
  • However, to identify which user is which, a unique session ID will be generated and saved in a cookie.

So yes, sessions are a better place to store sensitive information. For example, storing the users’ name, email, and ID in the session upon logging in.

 

SESSION EXPIRY

Take note that sessions have an expiry time as set in session.cookie_lifetime of php.ini. If the user clears the cookies, the session will also be lost.

 

INFOGRAPHIC CHEAT SHEET

Sessions In PHP (Click to Enlarge)

 

REFERENCES & LINKS

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “Sessions In PHP – Very Simple Examples”

Leave a Comment

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