PHP, Deny users access to the page during login?

How can I prevent a user from accessing a page when they are not logged in? I want it to be redirected to the login page. I know this has something to do with sessions.

+3
source share
4 answers

It works as follows:

  • Start Session: session_start ()
  • If Session ["user"] == null, redirect to the login page, continue.
  • On the login page, ask for the user password using the form
  • Submit this form on the login page
  • Verify your authentication (e.g. table in mysql) if user is logged in
  • , Session [ "user" ] = $userName, . , .

, , . . .

+7

- .

session_start();
if (!isset($_SESSION['nID']))
    header("Location: login.php");

session_start();
$_SESSION['nID'] = 1; //example
+8

, :

if (!isset($_SESSION['nID']))
    header("Location: login.php");

.. , . :

if (!isset($_SESSION['nID']))
{
    header("Location: login.php");
    die();
}

, , , . .

, $_SESSION ['nID'] , .

+8

:

login.php, , . ​​ login.php. ( = 'login.php'). , , ​​.

, , ($_POST['user']) . , $_SESSION :

$_SESSION['username'] = $_POST['user'];

, login.php :

echo 'header("login.php")'; //You should not have echoed anything before this

login.php , . , , inbox.php,

include ("login.php")

Now login.php will check if the 'user' session variable is set and allow access only to authorized users.

+1
source

Source: https://habr.com/ru/post/1720559/


All Articles