How to avoid UNLINK security risks in PHP?

后端 未结 7 1034
深忆病人
深忆病人 2021-01-12 18:59

I\'m using UNLINK with PHP and AJAX. I know that in this way is very dangerous, because everyone can delete any files. But I need to use AJAX

相关标签:
7条回答
  • 2021-01-12 19:25

    As Wadih M. has said. You need to authenticate your user. Then you can use that to compare the "Owner of the Image" to the "User currently log in". This will give you all the security you may want.

    As I said before, name the varaibles so that they sound right. When I see "id" in a varaiable. I automatically assume as a programmer that it is a numeric var.

    0 讨论(0)
  • 2021-01-12 19:33

    you can simplify your task by using a very simple database substitution - a directory structure. keep user's files in user's directory. so, you can always check if particular user has rights to delete. Name a directory after user's name, or - much better - numeric user id

    just something like

    $photo_id = basename($_GET['photo_id'];)
    $filename = $filebase.$_SESSION['user_id']."/".$photo_id;
    if (file_exists($filename) unlink ($filename);
    
    0 讨论(0)
  • 2021-01-12 19:33

    have had the same problem and got around it using PHP's ftp_delete function

    0 讨论(0)
  • 2021-01-12 19:42

    You need to authenticate the user somehow.

    Your user needs to be authenticated with a username and a password.

    PHP session can be used to remember, and you should use a database table or a text file on the server to store file ownership information.

    Then, before unlinking anything, your logic should make sure that the currently "authenticated" user is the owner of the file.

    0 讨论(0)
  • 2021-01-12 19:43

    Limit the unlinking to the directory with the photos. That is, do not allow .. in the path, or check the full path after doing realpath(). Otherwise, the user can request delete_photo.php?photo_id=../../../../etc/passwd and break the system.

    0 讨论(0)
  • 2021-01-12 19:45

    In your PHP:

    • Make sure $_GET['photo_id'] and $_GET['thumbnail_id'] don't contain "../"
    • Also make sure you prepend a basepath to the ID.

    Otherwise users can delete any file.

    As for the ownership, you have to store the information who owns which file somewhere on the server side (for example a MySql-DB). Then you should consult this location before deleting the file.

    0 讨论(0)
提交回复
热议问题