【问题标题】:Validation process when uploading an image in PHP vs creating an image from uploaded image在 PHP 中上传图像与从上传的图像创建图像时的验证过程
【发布时间】:2015-09-07 03:09:44
【问题描述】:

我的问题很简单。当我不让用户上传图片而是从源创建图片时,我是否应该进行彻底的验证?

我在想我只会使用$_FILES['file']['tmp_name'] 用 PHP 函数创建一个新的 jpeg 或 png 图像。

在 php.net 上我发现这个建议得票最多,我应该这样做还是有点矫枉过正?

try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // You should also check filesize here. 
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {
    echo $e->getMessage();
}

【问题讨论】:

    标签: php


    【解决方案1】:

    我认为你应该这样做(你的验证要彻底)。原因

    • 如果有人上传了有害的 php 文件怎么办?

    • 如果有人上传大文件怎么办?

    • 其他安全问题

    .
    需要进行彻底的验证,否则会对网站造成危险。验证所需的时间更少。因此安全性是最重要的。

    您在 php.net 上获得的代码会验证文件大小、扩展名等,这是完美的并将风险降至最低。

    同样从源创建图像需要更多资源。因此,最好让用户上传经过彻底验证的图像。 :)

    【讨论】:

    • 感谢您的回答。但这里的答案似乎不同意你:stackoverflow.com/questions/15595592/…。 “图像验证唯一可靠的方法是使用 GD 或 Imagick 对其进行复制”因此您不应该让用户上传图像以节省资源。还是我错了?
    猜你喜欢
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2011-06-22
    • 2012-07-25
    • 2018-01-03
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多