Sessions In PHP (Very Simple Guide & Examples)

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

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

That covers the quick basics, but just how do sessions 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.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes PHP Sessions Useful Bits & Links
The End

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

  • Sessions ride on top of cookies. It is highly recommended that you fully understand cookies before touching on sessions, read my other guide on cookies if you have missed it out.
If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

PHP SESSIONS

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

 

1) START SESSION

1A) PHP SESSION START

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

This is probably an insult to your intelligence. Just use session_start() to start the session… But what is session_id() and what goes behind is another story…

 

1B) HOW PHP SESSION WORKS

This can be quite brutal, so follow along. When session_start() is called:

  • PHP generates a unique session ID (we can use session_id() to get this session ID).
  • A session file sess_ID is created in the sessions folder (as defined in session.save_path in php.ini).
  • Lastly, send a PHPSESSID = ID cookie to the browser.

 

 

 

2) SAVING VARIABLES INTO THE SESSION

2A) PHP SET SESSION VARIABLES

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

No sweat. Just use $_SESSION like a “normal array” and assign all your values.

 

2B) WHERE SESSION DATA IS SAVED

Yep, this should not be a surprise. Whatever we assign in $_SESSION is actually saved in the session file on the server.

 

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_ID 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.

 

SESSION RESTRICTIONS

  • 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.
  • Sessions are file-based. If you are working with distributed servers, this will fail badly (unless you have some way to share the session file across different servers). Consider setting the session to save into a database instead. See the “cross-domain session” link below.

 

REFERENCES & LINKS

 

INFOGRAPHIC CHEAT SHEET

Sessions In PHP (Click to Enlarge)

 

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 Guide & Examples)”

Leave a Comment

Your email address will not be published.