【问题标题】:How to check file is valid image or not using php? [duplicate]如何检查文件是有效的图像或不使用 php? [复制]
【发布时间】:2018-11-21 08:08:35
【问题描述】:

我需要您对检查图像文件的建议。如果用户将上传任何扩展类型更改的文件,例如 (jpg,jpeg,bmp,png),我们如何在 PHP 中计算出来? 我不想只检查文件类型扩展,但我想通过更改它的扩展类型来知道上传的文件不是恶意文件。 比如:我们有 hack.php 文件,我们用 hack.jpg 文件对其进行了更改,所以我们如何识别这不是一个有效的文件。

【问题讨论】:

  • 为什么会有兴趣?如果用户上传了一些东西,那是他自己的问题。通常,您只想在请求时重新交付。如果有人上传了一个以某种方式重命名的文本文件,那么很好,他会得到一个文本文件。
  • 您自己做过什么吗?您应该尝试自己编写代码。请阅读How to create a Minimal, Complete, and Verifiable example
  • @arkascha 可能会使您的应用程序面临安全问题。
  • @FedericoklezCulloca 你能解释一下这是怎么可能的吗?
  • @FedericoklezCulloca 这需要server code that executes user provided data。一开始是个坏主意。

标签: php file file-type


【解决方案1】:

如果存在,我将使用mime_content_type。否则对文件执行file -i -b的linux命令得到答案。

考虑如下函数:

function getFileType($file_name) {
        if(! function_exists('mime_content_type')) {
            $isUnix = strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && DIRECTORY_SEPARATOR === '/';

            // check whether operating system is that of a UNIX type.
            if ($isUnix) {
                $type = null;
                exec('file -i -b ' . realpath($file_name), $type);
                $parts = @ explode(";", $type[0]); // can be of format text/plain;  charset=us-ascii 
                return trim($parts[0]);
            }

            // the file program/command does not exist on Windows.
            else {
                return null;
            }
        } else {
            return mime_content_type($file_name);
        }
    }

您也可以使用finfo-file 是您喜欢的。

【讨论】:

  • 或者你可以省掉自己的外壳并使用finfo_file
猜你喜欢
  • 2010-10-27
  • 2018-05-04
  • 2014-11-15
  • 2013-03-02
  • 1970-01-01
  • 2012-11-25
  • 2016-01-06
相关资源
最近更新 更多