Sessions in PHP ($_SESSION): Quick introduction

PHP Logo

Basic introduction:

Sessions in PHP help you store data in the browser that more than one PHP page can refer to, take Facebook for example, if you open 2 blank tabs in your web browser and in the first tab you sign in to your Facebook account, in the second blank tab if you goto the url: www.facebook.com it would take you to the same Facebook account as the first tab, this is because now your browser remembers your information from the first tab and uses that same information in the second tab. This is a very basic example, most websites use sessions to remember information from page to page. It’s also important to note that sessions are also supported by other scripting platforms such as jsp and Django (not the movie!).

Syntax for Sessions in PHP:

You can declare some variables(information) in one php page and use the same variables in another php page, this is how:

On the first php page:

sessions in php code1

page1.php

 

 

 

 

 

 

 

 

  • Don’t forget your semi-colons.
  • session_start() must come before everything else

After you run the first page (i.e you goto to the first page in your browser), id would now be temporarily stored in your browser as 126790 and the name variable would be stored as ‘ayo’.

On the second page where you want to re-use the information from the first page:

sessions in php code2

page2.php

  • Notice that session_start() also comes before every other thing in this page as well.
  • “.” dot represents concatenate, so in string that follows echo, there are 4 parts that are being concatenated together.
  • This would give the output: “The student number for ayo is 126790”

This is a very simple and quick example but sessions in php can be used for the transfer of more complex data from page to page and for many other important purposes.

For more on php sessions visit: http://www.php.net/manual/en/book.session.php

Share This

Comments are closed.