简体   繁体   中英

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.

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.

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.

Also, since you're looking for the first instance of "." your program will break with anything named something like 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命令:它检查文件的内容以推断其类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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