Cecil
Cecil

Reputation: 1619

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,

Upvotes: 0

Views: 153

Answers (4)

jerebear
jerebear

Reputation: 6655

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.

Upvotes: 1

Sander
Sander

Reputation: 1274

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.

Upvotes: 1

ChrisJ
ChrisJ

Reputation: 5241

If you're on Unix, you may use the file command: it examines the contents of the files to deduce their types.

Upvotes: 0

deceze
deceze

Reputation: 521994

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.

Upvotes: 2

Related Questions