Atomiklan Atomiklan - 21 days ago 10
Ajax Question

Using AJAX and PHP to validate a simple password

I have a hopefully simple problem to solve. We're trying to protect a link inside a secured part of our site with a simple password. Basically, inside our traditionally secured site, we have a dynamically driven table of records with a little padlock icon that toggles back and forth between locked and unlocked. This section of the site is already traditionally secured and accessible only to authorized users. We would therefore just like to implement this less secure static PHP password authentication system that allows users to lock and unlock records in this table. Essentially once they create a record in the table, they have the option to click the lock icon (which obviously locks the record), but only those with a simple hard coded pin can unlock a record once its locked (ie all users can lock, but not all users can unlock). I therefore tried to write a simple PHP + AJAX pin system. My other admin insisted on a server side solution. He refuses to use just basic javascript for this and I agree. It still needs a reasonable amount of security. Here is what I have so far, but I am very new (minutes) to AJAX and apparently something is not working. This is a single file named pin.php (so basically the page submits to itself)

The UNLOCK link simulates the lock icon which the user clicks to unlock the record.

<html>
<script src="js/jquery.js" type="text/javascript"></script>
<?php
$static_password = "1234";
if(isset($_POST['data'])){
$submit_password = $_POST['data'];
if($submit_password == $static_password){
echo "Do the unlock stuff";
}
else{
echo "Sorry try again";
}
}
?>
<body>
<h2>Simple AJAX PHP Example</h2>
<a href="javascript:Unlock();">UNLOCK</a>
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
console.log(response);
}
});
}
</script>
</body>
</html>


Any help is greatly appreciated. Thanks

Answer

This works for me as expected:

<?php
    $static_password = "1234";
    if(isset($_POST['data'])){
        $submit_password = $_POST['data'];
        if($submit_password == $static_password){
            die("Do the unlock stuff");
        }
        else{
            die("Sorry try again");
        }
    }
?><!DOCTYPE html><html>
<head>
    <script src="jquery-3.1.0.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Simple AJAX PHP Example</h2>
<a href="javascript:Unlock();">UNLOCK</a>
<script>
function Unlock() {
    var pin=prompt("You must enter pin to unlock");
    $.ajax(
    {
        url: 'pin.php',
        type: 'POST',
        dataType: 'text',
        data: {data : pin},
        success: function(response)
        { 
            console.log(response);
        }
    });
}
</script>
</body>
</html>