Radu033 Radu033 - 3 months ago 16
Ajax Question

Secure php -> Ajax delete item based on id

I'm building an app and I want the users to be able to delete some items.

I got this code for the delete button

<a class='delete_item' id='".$rs['id']."'><i class='icon-cancel'> </i></a>


The js file is called upon click

...
$.ajax({
type:'POST',
url:'set_order.php',
data:'delete_item='+item_id,
beforeSend: function() {
},
success:function() {
window.location.reload(true)
}
});
...


The set_order.php file opens and this code is processed

if($_POST['delete_item']) {
$id = $_POST['delete_item'];
$sql = "DELETE from list_items where ID = $id";
$query = $pdo->prepare($sql);
$query->execute();
}


Everything works fine, but it's not secured at all :) If the user inspects the page and changes the value of "id" as shown in this picture
enter image description here

And hits the "delete" button, the item with the id that the user changed will be deleted instead of the original id.

What is the best way to check the data?

Answer

Once you receive the request to delete an item check that they own the item and if they don't, don't delete it.

if(isset($_POST['delete_item'])){
    if(userOwnsItem($_SESSION['id'], $_POST['delete_item']){
       // Valid request
    }else{
       // Invalid request
    }
}

Where $_SESSION['id'] is the id of the user and the function userOwnsItem performs a query on the item and checks if the owner has the same id as the user.

Comments