PHP Sessions with Example – Programming Code Examples
PHP

PHP Sessions with Example2 min read

Sessions allow information to be stored during the visitor’s navigation on the site. They are often used for the authentication of a visitor, the management of a shopping cart, or any other application requiring the conservation of values between several pages.

Initializing the session variable




The session is initialized with session_start (). PHP then tries to read the identifier supplied by the user, searches for the corresponding file, and makes the information saved in the superglobal

$ _SESSION [] available to you.

Syntax: bool session_start (void)

Start a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let’s create a new page called “demo_session1.php”. In this page, we start a new PHP session and set some session variables:

Example:

Note: The session_start() function must be the very first thing in your document. Before any HTML tags.

Get PHP Session Variable Values

Next, we create another page called “demo_session2.php”. From this page, we will access the session information we set on the first page (“demo_session1.php”).

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION variable:

Example:

Another way to show all the session variable values for a user session is to run the following code:

Example:

 

Destroy a PHP Session

To destroy the current session, just call the php session_destroy () function.

 

Cookies

Cookies allow you to go further, and to keep data even after the session is closed, and will be the subject of a future tutorial.

Leave a Comment