Php – How to prevent a user from directly accessing the html page by writing URL

authorizationphp

i want a hard coded Login Page (login.html), with no database.
If a person writes correct username and password, it redirects to (page2.html).

Now my problem is that if a person write the URL directly for page2.html , he will be able to access it, without any login.

Ideal Case => www.example.com/login.html => if Correct => www.example.com/page2.html

Problem Case => www.example.com/page2.html => page2.html , NO LogIN 🙁

Best Solution

You can control all this with a php session like this

  //set the session on the login page
   $_SESSION['loggedIn'] = true;  

 //on the second page you check if that session is true, else redirect to the login page  
  if($_SESSION['loggedIn'])
      //allow
  else
      //redirect to the login page
      header('Location: /login.html');  

A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.

To make things simple, you can change your pages into php (e.g login.php).

  • Line 1: In your login.php page, you will first check if the username and password are correct, if they are, set the $_SESSION['loggedIn'] = true

  • Line 2: In your second page (page2.php), you will first check that the user did login by checking if the session have a value if($_SESSION['loggedIn']) {//allow processing}

  • Line 3: If that session variable is empty, then this means the user did not login, redirect him to the login page else { header('Location:/login.php');}
Related Question