简体   繁体   English

如何保护免受PHP中的文件上传攻击?

[英]How to protect from file upload attack in php?

I have file upload script as below (upload.php). 我有如下文件上传脚本(upload.php)。 As I can guess, someone can write script that sends 1000+ files to upload.php at the small period of time. 如我所料,有人可以编写脚本,在短时间内将1000多个文件发送到upload.php。

So, how to protect myself from numerous file uploads attack? 那么,如何保护自己免受众多文件上传攻击?

<?php
    if (!empty($_FILES)) {   
        $ds = DIRECTORY_SEPARATOR;
        $storeFolder = 'uploads';

        $rand_dir = rand(1, 1000);
        $targetPath = realpath(dirname(__FILE__) . '/..') . $ds . $storeFolder . $ds . $rand_dir . $ds;
        $targetPath_clean = $storeFolder . $ds . $rand_dir . $ds;

        if (!file_exists($targetPath))
            mkdir($targetPath, 0777, true);

        $filename = date('YmdHis_') . generateRandomString() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

        move_uploaded_file($_FILES['file']['tmp_name'], $targetPath . $filename);
        echo $targetPath_clean . $filename;
    } else {
        die('access denied');
    }
?>

This mainly depends on what you want to achieve. 这主要取决于您要实现的目标。

If form is anonymous you can use kind of capatcha or limit the file upload from one host (eg saving given IP in database and limiting its ability to upload further files). 如果表单是匿名的,则可以使用某种形式的capatcha或限制从一台主机上载文件(例如,将给定IP保存在数据库中,并限制其上载更多文件的能力)。 If your script requires user authorization you can limit file upload by given login. 如果脚本需要用户授权,则可以通过指定的登录名限制文件上传。

Please give us more details what is your business logic so we will be able to help you. 请提供更多详细信息,您的业务逻辑是什么,以便我们为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM