Good Way to Secure File Uploads in PHP

前端 未结 1 1715
醉酒成梦
醉酒成梦 2020-12-09 07:05

Writing a small app that (among other things) lets users upload a file (like an image, a .doc or a text file) as part of their posting/submission.

相关标签:
1条回答
  • 2020-12-09 07:34

    You have to do the following:

    1. Move all the files out of the webroot. You could disable access to the folder with .htaccess, but it is not worth the hassle and potential security risk. Just move it out there.
    2. Keep a table of the files uploaded, storing the user's original file name there. Rename the file to $id.$ext and so on. In short, you don't want to use the user's file name in your system.
    3. Have a script, download.php or whatever, get the file's ID, verify who is logged in, and if everything checks out, fetch the file, read it out to the browser, and send the appropriate download headers.

    These headers would be something like:

    header('Content-type: application/octet-stream');
    header('Content-disposition: attachment; filename=usersuppliedname.txt');
    header("Content-Length: " . filesize('../safefiles/1.txt'));
    header("Content-Transfer-Encoding:  binary");
    readfile('../safefiles/1.txt');
    exit;
    

    You can then get more fancy if you want to allow resuming files and such, but the above should do it.

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