How to check and create php session variables

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to check and create php session variable

In this article I’m going to show you some simple things to work with sessions in php, these are mostly used to store information about your users, like usernames, choices selected by users and similar, these however are stored on the server and deleted once the user closes the browser. To interact with session variables you need to carefully create them and then check them and accordingly do something based on their value. This is actually the main topic of this article, how to check and create php session variables.

Starting sessions …

It is imperative that you first and foremost start the session on your website, otherwise the session variables will be lost as soon as the page is refreshed or goes to a different page. This can be easily done using the session_start() php function.

It is important that you use the session_start() function before any other code on your website.

Creating php session variables

As you can see bellow, working wish session is similar to associative php arrays, the variable however needs to be $_SESSION. Then you create a session variable (more like an array element) by assigning it a value:

The above code will store the session variable ‘logged’ with the value ‘yes’ and based on this, you can probably show some specific links for a section that’s meant for logged users. Will show you in a second bellow.

How to check session variable

Checking the session variable is important, else you’re just storing them for nothing, you need to make use of them in certain ways. Bellow its an example of using the above ‘logged’ session variable:

Printing session variable

You can also print the session value wherever you need its value, for example:

Heads up! If you are testing this, do not forget that sessions are being stored until you close your browser or until you clear your browser cookies and cache! 

As you can see, this is not exactly hard, but needs a bit of attention. Sessions are normally used for logged section, where you rely on session to show account level section for your users.

Do not forget that this is only an example to see how session work, you will need to secure these if you really wish to use them in production … but that’s another article that may come soon.

That’s it for now, don’t forget to share and follow our website for new articles!

Request an article ←