Question

I am looking for a secure way of passing sensitive variables to a php file via ajax. At the moment i have been using data attributes but the values can be changed using something like firebug.

HTML:

<div class="strip">
    <?php
        if($hide == 0) {
            echo '<h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="0">Hide Business</h2>';
        }
        if($hide == 1) {
            echo '<h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="1">Un-Hide Business</h2>';
        }
    ?>
    <h2 class="action" data-type="1" data-id="<?php echo $id; ?>" data-action="2">Delete Business</h2>
</div>

JavaScript/JQuery:

$(".action").click(function() {
    var type = $(this).data("type");
    var id = $(this).data("id");
    var action = $(this).data("action");

    $.ajax({
        url : 'assets/php/confirm.php',
        type : 'POST',
        data : "type="+type+"&action="+action+"&ids="+id,
        success : function (result) {
            alert(result);
        }
    });
});

PHP:

if(isset($_POST['type'], $_POST['action'], $_POST['ids'])) {
    $type = $_POST['type'];
    $action = $_POST['action'];
    $ids = explode(",", $_POST['ids']);
    $count = count($ids);

    if($type == 0) {
        if($action == 1) {
            $stmt = $mysqli->prepare("DELETE FROM deals WHERE id=?");
        } else {
            $stmt = $mysqli->prepare("UPDATE deals SET hide=0 WHERE id=?");
        }
    } else {
        if($action == 1) {
            $stmt = $mysqli->prepare("DELETE FROM businesses WHERE id=?");
        } else {
            $stmt = $mysqli->prepare("UPDATE businesses SET hide=0 WHERE id=?");
        }
    }

    for($i = 0; $i < $count; $i++) {
        $stmt->bind_param('s', $ids[$i]);
        $stmt->execute();
        $stmt->close();
    }
    echo 'Success updated '.$_POST['ids'];
}

The variables that need to be secure are the data-type, data-id, data-action values. Reason being i dont want the wrong database entries being deleted. I dont know of any alternatives, so any help would be great.

Was it helpful?

Solution

If you want to stop the user changing them, then you can't get them from the user at all. Store the data on the server instead.

If you want to limit what values you'll accept from the user, then limit them on the server. Perform authentication and authorization. Make sure the values being changed are ones the logged in user is allowed to change.

OTHER TIPS

As your code on the client - inside the browser - can not be hidden, you should secure the connection between client and web server - use SSL/TSL for that...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top