⊗ppPmSsInr 317 of 447 menu

Sessions in PHP

When we see a site page in our browser, the PHP script of that page has long since finished working and forgotten about us. Therefore, if we navigate from one site page to another - the PHP script cannot remember data from the previous page, for example, variable values.

However, such a mechanism is very much needed, at least to remember the user's choice or that the user was authorized.

In PHP, sessions are intended for storing user data between site pages. We can write any information into the session and read it from there in the next run of this or another site script. Using sessions, we can implement user authorization, an online store shopping cart, and more.

The user session is stored on the server. It does not last forever, but only about half an hour - if the user does not make any requests to the site during this time, then their session will be deleted and become empty.

So, let's see how to work with sessions in PHP. To write something to the session, it first needs to be initialized using the function session_start:

<?php session_start(); ?>

After initialization, we can write something to the session or read something from it. This is done using the superglobal array $_SESSION.

Let's try it in practice. Let's create a file test1.php and place the following code in it:

<?php session_start(); $_SESSION['test'] = 'abcde'; // writing to the session ?>

And in the file test2.php - the following code:

<?php session_start(); echo $_SESSION['test']; // reading from the session ?>

Now, to start, open the file test1.php in your browser, and then test2.php. When opening the second file in the browser, it will display what was written to the session in the first file.

Create two files. When running the first file, write two numbers to the session, and when running the second file - display the sum of these numbers on the screen.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline