How to use PHP Sessions?

Need help with a simple PHP session tutorial?

Wondering what you should store in a session?

You are in the right place for a fun example:

If you are learning PHP, sooner or later you will have a need for using sessions.

Sessions allow you to maintain the state of an application between user requests.

They are useful when a user logs in to your site. So that you can recognize on each page that the user is still logged in as they navigate the pages of your site.

Once you understand how sessions work you might be tempted to store lots of data in the session. However sessions should generally be used to identify a user. Other data is saved in the database which is linked to the user / session.

Every PHP page which needs to access the session data will need to call this function first:

session_start();

You can then store and retrieve data in the session:

// To store a number in the session
$_SESSION['number'] = 911;
// To retrieve the store number
echo $_SESSION['number'];

The following in simple example of storing and retrieving sessions. This is a game of “Higher or lower?”, where you try and guess a number between 1 and 100. The code picks a random number and stores in it in the session when the game is started. Then as you attempt to guess, the cumulative number of guess is also stored in the session. When you win and correctly guess the number. It will retrieve the number of attempts from the session and display it.

Link to demo http://trabest.com/higher-or-lower.php
Link to github repo with the code https://github.com/element121/higher-or-lower

Try it out, the best number of guesses so far is 3!

Please leave a comment below and let me know what you think. If you any have questions, feel free to contact me.

Leave a Reply