Home > front end >  Prevent Direct access to PHP file using AJAX
Prevent Direct access to PHP file using AJAX

Time:03-16

I want to prevent direct access to a certain PHP file called prevented.php My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?

Here's my code:

index.php

<?php
  $_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
    $.ajax({
      type: "POST",
      url: "def.php",
      data: {
         token: '<?php echo $_SESSION["token"]; ?>'
      },
      cache: false,
      success: function(data) {
          console.log (data);
          if (data) {
            console.log (data   ' valid');
          } else {
            console.log (data   ' invalid');
          }
          location.href = "prevented.php";
      },
      error: function () {
        console.log('error');
      }
   });
</script>

def.php

<?php
    session_start();
    if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {    
       echo false;
       die('invalid in def');
    } else {
      define('_DEFVAR', 1);
      echo true;
      die ('valid in def');
    }
?>

prevented.php

<?php
   include "def.php";
   if (defined('_DEFVAR')) {
    die ('valid in prevented'); // instead of this I would show the content of the page
   } else {
       die ('invalid in prevented');
   }
?>

CodePudding user response:

Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.

index.php:

<?php
session_start();
$_SESSION['flag'] = true;
?>
<a href="protected.php">click here for the protected page</a>

protected.php:

<?php
session_start();
if ($_SESSION['flag'] ?? false) {
    echo "you have previously visited index.php";
} else {
    echo "you have not previously visited index.php";
}
?>
  • Related