⊗ppPmAuSs 415 of 447 menu

Authorization via Session in PHP

Our authorization should work as follows: a user, who wants to log in to the site, goes to the page login.php, enters the correct login and password and then browses the site's pages already being authorized.

For other pages of the site to know that our user is authorized, we must store a mark about this in the session.

For now, our authorization is not quite working, as we haven't connected the session yet and other pages of the site cannot determine if the user is authorized or not.

We will store the authorization mark in the session variable $_SESSION['auth'] - if true is written there, then the user is authorized, and if null - then not authorized.

Let's make the appropriate correction to our code:

<?php session_start(); if (!empty($_POST['password']) and !empty($_POST['login'])) { $login = $_POST['login']; $password = $_POST['password']; $query = "SELECT * FROM users WHERE login='$login' AND password='$password'"; $res = mysqli_query($link, $query); $user = mysqli_fetch_assoc($res); if (!empty($user)) { $_SESSION['auth'] = true; } else { // incorrect login or password entered } } ?>

Now on any page of the site we can check if the user is authorized or not, in this way:

<?php if (!empty($_SESSION['auth'])) { } ?>

You can close the text of some page entirely for an unauthorized user:

<?php if (!empty($_SESSION['auth'])): ?> <!DOCTYPE html> <html> <head> </head> <body> <p>text only for authorized user</p> </body> </html> <?php else: ?> <p>please log in</p> <?php endif; ?>

You can close only a part of the page:

<!DOCTYPE html> <html> <head> </head> <body> <p>text for any user</p> <?php if (!empty($_SESSION['auth'])) { echo 'text only for authorized user'; } ?> <p>text for any user</p> </body> </html>

Let our site, besides the page login.php, also have pages 1.php, 2.php and 3.php. Make it so that only an authorized user can access these pages.

Let our site also have a page index.php. Make it so that part of this page is open to all users, and part - only to authorized ones.

Modify your code so that upon successful authorization, the user's login is also written to the session.

Make it so that when visiting any page of the site, an authorized user sees their login, and an unauthorized one - a link to the authorization page.

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