【问题标题】:Check that an image is actually an image php检查图像是否实际上是图像 php
【发布时间】:2016-10-06 19:48:10
【问题描述】:

所以我有这个脚本用于将图像上传到服务器。 它允许 jpg 和 png 并将文件重命名为随机的 6 位数字。

<?php
if (isset($_FILES['file'])) {
    $file       = $_FILES['file'];
    $file_name  = $file['name'];
    $file_tmp   = $file['tmp_name'];
    $file_size  = $file['size'];
    $file_error = $file['error'];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array(
        'jpg',
        'png'
    );

    if (in_array($file_ext, $allowed)) {
        if ($file_error === 0) {
            if ($file_size <= 10000000) {
                $file_name_new    = mt_rand(100000, 999999) . '.' . $file_ext;
                $file_destination = 'files/' . $file_name_new;
                if (move_uploaded_file($file_tmp, $file_destination)) {
                    echo "<a href='$file_destination'>$file_name_new</a>";
                }
            }
        }
    }
}
?>

一切都很好。它只允许具有指定扩展名 .jpg 和 .png 的文件。

我遇到的问题是您可以将 script.txt 等 txt 文件重命名为 script.txt.jpg 并且服务器会允许这样做,但是它实际上不是图像。这提供了攻击的脆弱性。

我是否可以添加一些内容来实际验证正在上传的文件是图像?我听说过一些关于 getimagesize 的信息,但我不确定。我对php很陌生。

【问题讨论】:

标签: php file-upload image-uploading


【解决方案1】:

您需要使用文件的 mimetype 来知道它是什么类型的文件。扩展名不相关。

确实,您可以为此使用getimagesize

<?php 
    ...
$size = getimagesize($file_name)); 

switch ($size['mime']) { 
    case "image/gif": 
        echo "Image is a gif"; 
        break; 
    case "image/jpeg": 
        echo "Image is a jpeg"; 
        break; 
    case "image/png": 
        echo "Image is a png"; 
        break; 
    case "image/bmp": 
        echo "Image is a bmp"; 
        break; 
} 
?>

来源:http://php.net/manual/en/function.image-type-to-mime-type.php

【讨论】:

    猜你喜欢
    • 2016-07-20
    • 2017-06-11
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多