Php 上载时检查文件类型,以及浏览器依赖性问题
我正在构建一个php文件上传程序,我遇到了一些安全问题。例如,我不想允许上载“.php”文件。据我所知,检查文件类型的唯一方法是使用Php 上载时检查文件类型,以及浏览器依赖性问题,php,mime-types,Php,Mime Types,我正在构建一个php文件上传程序,我遇到了一些安全问题。例如,我不想允许上载“.php”文件。据我所知,检查文件类型的唯一方法是使用$\u FILES['file']['type'],其值取决于浏览器 我检查了多个浏览器,发现当选择一个常规的.php文件时,不同的浏览器返回以下值: firefox: application/x-download chrome: text/plain safari: text/plain IE: text/plain opera: application/octe
$\u FILES['file']['type']
,其值取决于浏览器
我检查了多个浏览器,发现当选择一个常规的.php文件时,不同的浏览器返回以下值:
firefox: application/x-download
chrome: text/plain
safari: text/plain
IE: text/plain
opera: application/octet-stream
我也尝试过使用常规的.txt文件进行相同的实验,所有的浏览器都返回text/plain
作为mime类型
问题是,如果我想允许.txt文件上传,我应该做什么来阻止.php文件上传?不要依赖客户端发送的信息。甚至客户端发送的媒体类型也可以伪造 如果不允许使用PHP文件,请不要使用文件扩展名为
.PHP
的文件或将其更改为.txt
:
if (strtolower(strrchr($_FILES['file']['name'], '.')) == '.php') {
// has file extension .php
}
尝试以下方法。这远非万无一失,但它是一个快速检查。它将阻止任何标记为.php的内容(就像在客户端机器上一样),因此如果它们有类似“do_evil.php.txt”的内容,它将允许它,但是(请阅读代码注释)
我过去曾在下降结果中使用过上述方法。它绝不是防弹的,但至少应该有帮助。我想我可能有一些代码可以实现所有这些功能,如果您需要,我会去找它,但没有承诺我可以找到它使用以下功能:
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类型。这也将只阻止“php”或“foo.notphp”。大多数人不会删除他们的文件扩展名(如果他们有),谁会给文件一个。不是吗???分机?但是你的权利。正如我所说的,它远不是傻瓜式的,但作为一个stop-gapI,它更喜欢使用以下代码来确定扩展名:$extention=strtolower(end(explode('.',$u FILES['userfile']['name']);出于安全原因,还必须在允许文件上载的目录中禁用php。(如果您的主机在默认情况下也解释.php3文件,而您无法捕获该文件,等等)在.htaccess文件中使用“php_flag engine off”使用此代码,我从各种文件类型中得到了很多错误。。。尤其是那些来自OpenOffice的。
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;
}