John Davidson

javascript - Prevent Direct access to PHP file using AJAX

0 comments
Message:


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');
}
?>


My Answer:
"prevented.php". This way, the prevented.php file can only be accessed if the token validation is successful.

Here is an example of how you can implement this logic:

index.php:
php
session_start();
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
?>




Prevent Direct Access









def.php:
php
session_start();

if ($_SESSION['token'] == $_POST['token']) {
define('_DEFVAR', true);
echo 'true';
} else {
echo 'false';
}
?>


prevented.php:
php
if (!defined('_DEFVAR')) {
header('Location: index.php');
exit;
}
?>



Prevented Page


This is a prevented page






In this example, when you click the button in index.php, it will call def.php using AJAX and pass the token generated in index.php. If the token validation is successful, it will define _DEFVAR and redirect to prevented.php. If the token validation fails, it will display an alert message.

Rate this post

3 of 5 based on 9317 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us