编程语言
首页 > 编程语言> > php-上传时检查文件类型以及浏览器依赖性问题

php-上传时检查文件类型以及浏览器依赖性问题

作者:互联网

我正在构建一个php文件上传器,但在安全性方面存在一些问题.例如,我不想允许“ .php”文件上传.据我所知,检查文件类型的唯一方法是使用$_FILES [‘file’] [‘type’],其值取决于浏览器.

我检查了多个浏览器,发现在选择常规.php文件时,其他浏览器会返回以下值:

firefox: application/x-download
chrome: text/plain
safari: text/plain
IE: text/plain
opera: application/octet-stream

我还尝试过对普通的.txt文件进行相同的实验,并且所有浏览都将文本/纯文本作为mime类型返回.

这就是问题所在,如果我想允许.txt文件上传,应该怎么做才能防止.php文件上传?

解决方法:

使用以下功能:

function Mime($path)
{
    $result = false;

    if (is_file($path) === true)
    {
        if (function_exists('finfo_open') === true)
        {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            if (is_resource($finfo) === true)
            {
                $result = finfo_file($finfo, $path);
            }

            finfo_close($finfo);
        }

        else if (function_exists('mime_content_type') === true)
        {
            $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path));
        }

        else if (function_exists('exif_imagetype') === true)
        {
            $result = image_type_to_mime_type(exif_imagetype($path));
        }
    }

    return $result;
}

这将返回任何文件的正确的MIME类型.

标签:mime-types,php
来源: https://codeday.me/bug/20191024/1919302.html