如何使用php检查文件是否有效?

时间:2018-11-21 08:08:35

标签: php file file-type

我需要您的建议来检查图像文件。如果用户将上传任何扩展名已更改的文件,例如(jpg,jpeg,bmp,png),我们如何在PHP中找出答案? 我不想仅检查文件类型扩展名,但我想知道通过更改扩展名类型,上传的文件不是恶意文件。 就像:我们有hack.php文件,并用hack.jpg文件进行了更改,因此我们如何识别这不是有效文件。

1 个答案:

答案 0 :(得分:0)

如果存在,我将使用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