Welcome Guest, Not a member yet? Register   Sign In
Identifying uploaded files with mime type application/octet-stream as images
#1

[eluser]kallus[/eluser]
We had a problem with some devices (playstation portable) setting the mime type to application/octet-stream instead of image/jpeg or image/gif etc. for uploaded image files (hence making the upload library reject the files as non-images). I wrote this code that uses the php extension Fileinfo to read the files magic bytes and replaces the very generic application/octet-stream type with a more specific one. Might be something to add to the CI uploading library. (Downside is that the Fileinfo extension needs to be installed on the server)

Code:
//if mime type is application/octet-stream (psp gives jpegs that type) try to find a more specific mime type
$mimetype = strtolower(preg_replace("/^(.+?);.*$/", "\\1", $_FILES['form_field']['type'])); //reg exp copied from CIs Upload.php
if($mimetype == 'application/octet-stream'){
    $finfo = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
    if($finfo){
        $_FILES['form_field']['type'] = finfo_file($finfo, $_FILES['form_field']['tmp_name']);
        finfo_close($finfo);
    }
    else echo "finfo_open() returned false");
}

I do this before calling $this->upload->do_upload('form_field'), but it could as well be done in an extension to the uploading library.
#2

[eluser]Chris Newton[/eluser]
Tried to add this to a recent script... but Dreamhost doesn't have the Fileinfo extension installed by default. I guess you can compile your own version of PHP, but it's for an internal project and I don't have time to get into all that. Regardless, I saw this months ago, and I still think it's a great idea, and great little extra. Thanks.

BTW, in the script above, there's an extra ) at the end of the echo statement.
#3

[eluser]Monarobase[/eluser]
Hello,

I don't know what it's worth security or ressource wise but what about the following approach to get the mime type :

Code:
function _getmime($file){
    if($info = @getimagesize($file)) {
        return image_type_to_mime_type($info[2]);
    } else {
        return mime_content_type($file);
    }
}

This method doesn't need a specific php install and so far has returned the correct mime type on all files I have tested so far, even with the wrong file extension...




Theme © iAndrew 2016 - Forum software by © MyBB