简体   繁体   English

PHP-检查文件类型

[英]PHP - Checking file types

I have written a little bit of code for checking a file input for the extension and only letting through if its allowed but it doesnt seem to be working. 我已经编写了一些代码来检查扩展名的文件输入,并仅在允许的情况下通过,但似乎无法正常工作。

I call the function by using the following: 我使用以下命令调用该函数:

$vcFileType = check_filetype($HTTP_POST_FILES['cv']['name'],"That filetype isnt allowed punk",array('doc','docx','pdf'));

and the function is as follows: 其功能如下:

function check_filetype($file, $problem='', $types){
    $fileExt = substr($file, strrpos($file, '.') + 1);
    if(in_array($fileExt, $types)){
        show_error($problem);
    }
    return $file;
}

If someone could let me know where im going wrong, that would be grand. 如果有人能让我知道我要去哪里错了,那将是很大的事情。

Cheers, 干杯,

if (in_array($fileExt, $types)) {
    show_error($problem);
}

"If the extension is one of the allowed extensions, show the error..." “如果扩展名是允许的扩展名之一,请显示错误...”

Apart from this logic glitch: never trust the user supplied file name! 除了这种逻辑故障之外:永远不要相信用户提供的文件名!
It's completely arbitrary and easily faked. 它是完全任意的,很容易伪造。
Try to actually process the file or find its MIME type instead. 尝试实际处理文件或查找其MIME类型

Exactly, checking a file name for it's extensions is not a save way to go. 确实,检查文件名的扩展名不是保存的方法。 Someone can still hide a malicious file in a PDF file for example. 例如,仍然有人可以将恶意文件隐藏在PDF文件中。

Checking for an extension can be a good way for an initial check though to skip the mime check if the extension is not right already. 检查扩展名可能是进行初始检查的好方法,但是如果扩展名不正确,则可以跳过哑剧检查。

It looks like you're only grabbing the first character of the extension. 看来您只是在抓住扩展程序的第一个字符。 string position + 1. 字符串位置+1。

Also, since you're looking for the first instance of "." 另外,由于您要查找“。”的第一个实例。 your program will break with anything named something like inc.functions.php. 您的程序将以诸如inc.functions.php之类的名称中断。

try this instead: 试试这个代替:

function check_filetype($file, $problem='', $types){
    $file_parts = explode(".", $file);
    $fileExt = array_pop($file_parts);
    if(in_array($fileExt, $types)){
        show_error($problem);
    }
    return $file;
}

This will turn the file name into an array based on the "." 这会将文件名转换为基于“。”的数组。 regardless of how many many be in the name and then return the last element of that array - the extension. 不管名称中有多少,然后返回该数组的最后一个元素-扩展名。

如果您使用的是Unix,则可以使用file命令:它检查文件的内容以推断其类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM