简体   繁体   中英

PHP: Restricting access to the final page

I'm trying to restrict the acccess to a php page. The file "calendario.php" should be only visible for the users previously logged on through "login.php"

The problem right now: if the user type manually the url in the browser, he can accesss directly without credentials. I managed to prevent this with a "if" but even so .The page loads the content for a moment, so if you are skilled enough you can pause the browser in the exact momento and have access to the information.

This is what I tried so far:

login.php

<?php
   include("required/datos.php");
   session_start();

   if($_SERVER["REQUEST_METHOD"] == "POST") {

      $myusername = mysqli_real_escape_string($db,$_POST['login']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']); 

      $sql = "SELECT * FROM usuarios WHERE login = '$myusername' and BINARY password = '$mypassword'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);


      $count = mysqli_num_rows($result);


      if($count == 1) {
         $_SESSION['login_user'] = $myusername;
         $_SESSION['autorizado'] = TRUE;
         header('location: calendario.php');

      }else {

         $message = "Credenciales incorrectas";
         echo "<script type='text/javascript'>alert('$message');</script>";
         header('Refresh: 0; URL=index.php');


      }
   }
?>

calendario.php

<?php

require_once('required/bdd.php');
session_start(); 
?>

<?php
  if($_SESSION['autorizado']==true)
    { 

      echo '<li class="active" style="padding-left: 15px">';
      echo $_SESSION["login_user"];
      echo ' - ';
      echo '<a href="logout.php"><span>Desconectar</span></a></li>';
    }
  else
    {
      header('Refresh: 0; URL=index.php');
    }

?>

<?php

$sql = "SELECT id, title, start, end, color FROM events ";

$req = $bdd->prepare($sql);
$req->execute();

$events = $req->fetchAll();


?>

I would like to know your opinion on how to improve this. Thank you.

  1. Use a proper redirect with a Location header
  2. Don't output the content if they aren't authorised to see it. Stop the script before it gets to the part that generates the content.

Such:

{
  header('Location: index.php');
  exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM