Removing local files and database records using AJAX

I am using ajax to delete files from database and local. No problem on the database side. However, I am unable to remove the correct file from the local. I think I can't pass the correct filename ... It deletes the local file at the top of the page.

My index.php file:

<p><?php echo $file->name; ?></p>

<input type="hidden" name="file-name" value="<?php echo $file->name; ?>">

<button name="delete" id="delete" value="<?php echo $file->id; ?>">
    <span>DELETE</span>
</button>

      

My delete.php file:

if(isset($_POST['deleteFile'])) {

    $delFile = $db->execute("DELETE from files WHERE id='{$_POST['id']}'");
    $fname = 'upload/'.$_POST['fname'];

    if($delFile){
        unlink($fname);
        echo "File is deleted!";
    }

    else{
        echo "There was a problem!";
    }

}

      

JS file:

$('body').delegate('#delete','click',function(){

    var idDelete = $(this).val();
    var nameDelete = $("input[name=file-name]").val();
    var parent = $(this).parent().parent();

    if(confirm){
        $.ajax({
            url   : "delete.php",
            type  : "POST",
            async : true,
            data  : {
                deleteFile : 1,
                id : idDelete,
                fname : nameDelete,
            },
            success: function()
               {
                parent.fadeOut('slow', function() {$(this).remove();});
               }

        });
    }
});

      

+3


source to share


1 answer


This is more like "teach a man to fish" rather than an exact answer, because it is difficult to tell from your code why this file may or may not be deleted.

First, since others have said that your code is extremely dangerous and has the ability for someone to delete any file on your system - never trust user input. You may also have an SQL injection vulnerability.

But as far as your problem is, you cannot see what is going on because you are ignoring or masking errors with your code. To provide some visibility, I would do this:

if($delFile){
    $fname = __DIR__ . '/' . $fname;
    if (unlink($fname)) {
        echo "File is deleted!";
    }
    else {
        throw new Exception("Unable to delete file with name " . $fname);
    }

}
else{
    throw new Exception("Unable to delete DB record with id " . $_POST['id']);
}

      



Then there will be something in your javascript that will output the ajax results to the console so you can see what the filepath is looking for

if(confirm){
    $.ajax({...},
        success: function(){...},
        error: function(jqXHR){console.log(jqXHR.responseText);}

    });
}

      

This error will probably not be fixed, but it will allow you to see what is going on, which could be a simple error in the file path.

0


source







All Articles