【问题标题】:How to protect from file upload attack in php?如何防止php中的文件上传攻击?
【发布时间】:2015-07-29 17:06:44
【问题描述】:

我有如下文件上传脚本(upload.php)。我可以猜到,有人可以编写脚本,在短时间内将 1000 多个文件发送到 upload.php。

那么,如何保护自己免受大量文件上传攻击?

<?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');
    }
?>

【问题讨论】:

  • 不可能。 php 在上传完成后才会运行。在 php 中实际上没有什么可以防止问题发生。
  • 如果有 1000+ 个合法用户同时尝试向 upload.php 发送文件怎么办?

标签: php security file-upload


【解决方案1】:

这主要取决于你想要达到什么。

如果表单是匿名的,您可以使用某种验证码或限制从一台主机上传文件(例如,将给定 IP 保存在数据库中并限制其上传更多文件的能力)。如果您的脚本需要用户授权,您可以通过给定登录限制文件上传。

请向我们提供更多详细信息,您的业务逻辑是什么,以便我们为您提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-12
    • 2023-03-14
    • 1970-01-01
    • 2017-03-31
    • 2011-03-21
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多