Rectangle 27 4

Some androids indeed upload using mime-type application/octet-stream instead of the correct one.

//the uploaded file
$img = $_FILES['img'];

//array for type if octet
$realMime = array(
    'useNew' => false,
    'type' => '' 
);

if($img['type'] == "application/octet-stream"){
    $imageMime = getimagesize($img['tmp_name']); // get temporary file REAL info
    $realMime['type'] = $imageMime['mime']; //set in our array the correct mime
    $realMime['useNew'] = true; //set to true for next if
}

//now check if we will use the realMime or the one sent by browser
//$mimeCheck is the things you want to check. In my case i just wanted PNG or JPG
if($realMime['useNew'] == true){ //if true, use realMime to check
    $mimeCheck = ($realMime['type'] != "image/png" && $realMime['type'] != "image/jpeg" && $realMime['type'] != "image/jpg");
}else{ //if not using real mime, go with the one browser sent us
    $mimeCheck = ($img['type'] != "image/png" && $img['type'] != "image/jpeg" && $img['type'] != "image/jpg");
}

//returns error if image not png/jpg/jpeg
if($mimeCheck){
    //return some error
}

With this you can check. Of course have to make an error handler for getimagesize() since user can upload an octet-stream file that isn't really an image.

Android image file sent to php upload image file is application/octet-...

php android
Rectangle 27 3

application/octet-stream or image/jpeg is only the mime-type the HTTP client (browser) has added as additional information next to the binary file-data itself.

So the mime-type shouldn't be of any issue here. It's just that you see a difference between the requests for the case your program fails, but this must not be the cause of your issue.

Instead you should add error and condition checking to your code. Especially precondition checks so that you know that your script can properly operate on the data it gets provided.

From what you have made visible in your question, there is nothing more specifically I can add. Hope this is helpful anyway.

Also the PHP Manual has a section about file-uploads which contains some useful information incl. dealing with error-cases.

Next to that your code might just have a problem with how you insert the data into your database, so the problem might not be related at all with the file-upload technically.

Still a bit lost, never been so stuck in a solution. Thx for your answer hakre, but if I add error checking then I'm just creating a problem on my android side of things its forever going to be rejected.

$data = file_get_contents($_FILES['uploaded']['tmp_name']); $image = imagecreatefromstring($data); Was hoping to using something like the above but keeps failing.

Android image file sent to php upload image file is application/octet-...

php android
Rectangle 27 2

There's no clean way of doing this, I'm afraid. You could use the @ syntax to upload an existing file (and then cURL specifies the octet-stream and also uses the file name you supplied in filename. But you can't specify an empty filename that way.

You can do this... a multiline injection attack against your own code. cURL doesn't seem to mind, but I don't know if it is by design, to allow you to do the dirty deed, or if it is by accident and might stop working in the next release:

$dataArray['attchmnt[0]"; filename=""'."\r\n".'Content-Type: octet-stream'] = '';
0x0a30:  2d2d 2d2d 2d2d 2d2d 2d2d 2d2d 2d2d 2d2d  ----------------
    0x0a40:  2d2d 2d2d 2d2d 2d2d 2d2d 2d33 6331 3837  -----------3c187
    0x0a50:  3162 6630 3132 360d 0a43 6f6e 7465 6e74  1bf0126..Content
    0x0a60:  2d44 6973 706f 7369 7469 6f6e 3a20 666f  -Disposition:.fo
    0x0a70:  726d 2d64 6174 613b 206e 616d 653d 2261  rm-data;.name="a
    0x0a80:  7474 6368 6d6e 745b 305d 223b 2066 696c  ttchmnt[0]";.fil
    0x0a90:  656e 616d 653d 2222 0d0a 436f 6e74 656e  ename=""..Conten
    0x0aa0:  742d 5479 7065 3a20 6f63 7465 742d 7374  t-Type:.octet-st
    0x0ab0:  7265 616d 220d 0a0d 0a0d 0a2d 2d2d 2d2d  ream"......-----
    0x0ac0:  2d2d 2d2d 2d2d 2d2d 2d2d 2d2d 2d2d 2d2d  ----------------
    0x0ad0:  2d2d 2d2d 2d2d 2d2d 2d33 6331 3837 3162  ---------3c1871b
    0x0ae0:  6630 3132 362d 2d0d 0a                   f0126--..

which should be what you're after.

// $dataArray as defined by you

// Change the 'attchmnt[0]' entry
$dataArray['attchmnt[0]"; filename=""'."\r\n".'Content-Type: octet-stream'] = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER,         False);
curl_setopt($ch, CURLOPT_VERBOSE,        False);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_URL,            'http://127.0.0.1/');
curl_setopt($ch, CURLOPT_POST,           True);
curl_setopt($ch, CURLOPT_POSTFIELDS,     $dataArray);
curl_exec($ch);

I added that after the line declaring the $dataArray and it just appeneded to the array. I also tried replacing 'attchmnt[0]' => 'filename="";type=application/octet-stream', with 'attchmnt[0]"; filename=""'."\r\n".'Content-Type: octet-stream' >= '', and that didn't do anything to the array at all. Could you explain a little more?

Attached test code. But I don't understand how changing an entry could have done "nothing to the array at all"... you do nothing else to that array before sending it to cURL, right?

Nice idea, this helped me with TwitterAPI's statuses/update_with_media. i wasn't able to upload contents of an image from memory until i used this trick. Thanks.

How do you get rid of the extra double quotes it's adding after the end of octet-stream"

This kludge keeps getting dirtier and dirtier. Have you tried appending another \r\n immediately after octet-stream? It looks like we should give up with cURL and use straight socket I/O.

PHP - Curl - multipart/form-data with application/octet-stream for a b...

php file curl upload multipartform-data
Rectangle 27 2

You're correct, uploadify uses the mime type application/octet-stream for most (all?) the files which it uploads. I think this is actually caused by Flash handling the uploading, but I'm not 100% sure.

In your controller where you handle the upload, drop in a print_r($_FILES) and check out what the mime-type is, then just add it to your application/config/mimes.php file.

So in your mimes.php file you'll probably have something like:

'jpg'   =>  array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),

The problem is that a user can figure out the url to which uploadify uploads, and then he can upload any malicious file manually to that url and pass on the mime type octet-stream, and it will be accepted. I've instead settled for getImageSize() to confirm if a file's an image or not.

Yes, this is an issue, unfortunately it is an issue with Uploadify. Two possible solutions are recreating the uploaded image via PHP's GD library after the upload (any non-image file will throw an error) or find another upload script.

php - Strange CodeIgniter file upload error - Stack Overflow

php codeigniter upload mime-types uploadify
Rectangle 27 35

In times like these, the official HTTP specification is always helpful. From RFC 2616 7.2.1 (my emphasis added):

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

The cause of your issue is that the server accepting the file upload does not itself know what type of file has been uploaded. Why? Because it relies on the the HTTP message which sent the file to specify a Content-Type header to determine the exact mime-type. The browser has likely not sent a Content-Type header and the server has assumed application/octet-stream as per the official HTTP specification excerpt above. It's also possible that the client uploading the file opted not to determine the mime type of the file it was uploading and sent the Content-Type: application/octet-stream header itself.

$_FILES['userfile']['type']

So as you can see, even if $_FILES['userfile']['type'] is specified, it only corresponds to the Content-Type header sent by the client. This information can easily be faked and should not be relied upon. If you need to be sure that the uploaded file is of a specific type, you'll have to verify that yourself.

php - Why am I getting mime-type of .csv file as "application/octet-st...

php csv http-headers mime-types file-format
Rectangle 27 35

In times like these, the official HTTP specification is always helpful. From RFC 2616 7.2.1 (my emphasis added):

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

The cause of your issue is that the server accepting the file upload does not itself know what type of file has been uploaded. Why? Because it relies on the the HTTP message which sent the file to specify a Content-Type header to determine the exact mime-type. The browser has likely not sent a Content-Type header and the server has assumed application/octet-stream as per the official HTTP specification excerpt above. It's also possible that the client uploading the file opted not to determine the mime type of the file it was uploading and sent the Content-Type: application/octet-stream header itself.

$_FILES['userfile']['type']

So as you can see, even if $_FILES['userfile']['type'] is specified, it only corresponds to the Content-Type header sent by the client. This information can easily be faked and should not be relied upon. If you need to be sure that the uploaded file is of a specific type, you'll have to verify that yourself.

php - Why am I getting mime-type of .csv file as "application/octet-st...

php csv http-headers mime-types file-format
Rectangle 27 1

'xls'   =>  array('application/excel', 'application/vnd.ms-excel', 'application/vnd.ms-office', 'application/octet-stream', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/x-zip', 'application/vnd.ms-excel', 'application/msword'),
'xlsx'  =>  array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/x-zip', 'application/vnd.ms-excel', 'application/msword'),

php - CodeIgniter: Excel file upload Error - Stack Overflow

php codeigniter file-upload
Rectangle 27 2

Never heard of application/octet. Guessing it is just equivalent to application/octet-stream. It is just the catch all anyway.

The MIME types "text/plain" and "application/octet-stream" are termed ambiguous because they generally do not provide clear indications of which application or CLSID should be associated as the content handler...

defaulting to the final determined MIME type of "application/octet-stream."

Finally, if no file name extension is found, or one is found with no associated MIME type or registered application, the MIME type "text/plain" is returned if the data scan indicated predominantly text, or "application/octet-stream" if the data scan indicated binary, because this is the furthest correct determination that could be made.

php - Mime type of uploaded zip file is application/octet - Stack Over...

php upload mime-types
Rectangle 27 3

today Zend Framework is 1.11.10 and resolution of this issue is not backported from ZF2. here is bug report.

here is the patch. the idea of the patch is that in php5.3 mimefile is included with php and we don`t need anymore external file.

also, to make use of this fix you should add validator like this:

$upload->addValidator('IsImage', false, array('magicfile'=>false));

Good answer. My issue was certainly outdated ZF1 Zend_Validate_File_MimeType. Love deleting lines of code to fix an issue.

php - file->getMimeType() always returns application/octet-stream with...

php zend-framework mime-types file-upload
Rectangle 27 1

At Android side to make proper call we should make the web-service call like this:

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("https://someserver.com/api/path/");
        postRequest.addHeader("Authorization",authHeader);
        //don't set the content type here            
        //postRequest.addHeader("Content-Type","multipart/form-data");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);


        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        reqEntity.addPart("parm-name", new InputStreamBody(fileInputStream,"image/jpeg","file_name.jpg"));

        postRequest.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(postRequest);

        }catch(Exception e) {
            Log.e("URISyntaxException", e.toString());
        }

Android image file sent to php upload image file is application/octet-...

php android
Rectangle 27 61

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

You should always check the content, this method could easily fail when a file is actually a csv but has some strange mime type like application/x-msdownload. CSV can be application/x-msdownload, but XLS can also, so this is bad.

-1. This code is wrong. It depends on what the user's browser thinks is the correct MIME type of a file name ending in .csv. Also, if the user renames a .jpeg to end in .csv, this code will still allow it as valid. For a quick sanity check as per the asker's comment (Ie. that the user didn't accidentally select the wrong file), it is far simpler to check the file name extension. To see if the CSV file is valid for your application, attempt to process the CSV file as per your application's rules; if it fails, it's not valid.

php - Check file uploaded is in csv format - Stack Overflow

php syntax file-upload content-type
Rectangle 27 7

text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext

There are various MIME types for CSV.

Your probably best of checking extension, again not very reliable, but for your application it may be fine.

$info = pathinfo($_FILES['uploadedfile']['tmp_name']);

if($info['extension'] == 'csv'){
 // Good to go
}

I would think you would check againsts $_FILES['uploadedfile']['name'] vs. tmp_name as tmp_name is the temporary file name on the server. At least in my case, the tmp_name does not include the original file extension.

php - Check file uploaded is in csv format - Stack Overflow

php syntax file-upload content-type
Rectangle 27 5

Some providers does not allow you change certain values in running time. Instead of this, try to either change it in the real php.ini file or use an .htaccess (For Apache web servers) where you can add your configuration. You can find more information in the PHP.net article about this subject: How to change configuration settings.

<IfModule mod_php5.c>
php_value upload_max_filesize 100000000
php_value post_max_size 110000000
php_value memory_limit 120000000
php_value max_input_time 20
</IfModule>

This isn't a provider its an in house server, but I personally don't have access to the httpd.conf file. I guess my only option is using the .htaccess file. There aren't really any examples on the page you linked to, I'm guessing the correct syntax I should use in the .htaccess file is "php_value upload_max_filesize '6M'" with AllowOverride All set?

Yes, your Apache directive for that host should have AllowOverride All.

I used this as the contents of my .htaccess file - I don't know how to correctly put this in code brackets [code]<Directory /> Allowoverride All </Directory> <IfModule mod_php5.c> php_value upload_max_filesize 100000000 php_value post_max_size 110000000 php_value memory_limit 120000000 php_value max_input_time 20 </IfModule>[/code]I was guessing with the syntax I proposed was this correct or were you using my guess for the code you gave me?

Allowoverride All
httpd.conf

Ahh, so if that is not set in the httpd.conf file then my only option is to in some way contact out server administrator? And have him change the configuration in the real php.ini file, the httpd.conf file, or give me access to either of those?

php file upload error of 1 - What is correct way to use php_ini? - Sta...

php file-upload php-ini
Rectangle 27 2

Solution: add application/netfabb to the section of allowed mime types. This is the mime type most browsers assign to .stl files. Firefox is an exception and identifies .stl files as application/octet-stream.

php - upload form only works in Firefox when uploading ASCII .stl 3D f...

php forms post mime-types
Rectangle 27 1

public function uploadImage() {
        $this->load->helper(array('form', 'url'));  
        $config['upload_path'] = 'assets/images/b2bcategory';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '1000';
        $config['max_width'] = '2024';
        $config['max_height'] = '1768';
        $config['width'] = 75;
        $config['height'] = 50;
        if (isset($_FILES['catimage']['name'])) {
            $filename = "-" . $_FILES['catimage']['name'];
            $config['file_name'] = substr(md5(time()), 0, 28) . $filename;
        }
        $config['overwrite'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $field_name = "catimage";
        $this->load->library('upload', $config);
        if ($this->input->post('selsub')) {
            if (!$this->upload->do_upload('catimage')) {
                //no file uploaded or failed upload
                $error = array('error' => $this->upload->display_errors());
            } else {
                $dat = array('upload_data' => $this->upload->data());
                $this->resize($dat['upload_data']['full_path'],           $dat['upload_data']['file_name']);
            }
            $ip = $_SERVER['REMOTE_ADDR'];
            if (empty($dat['upload_data']['file_name'])) {
                $catimage = '';
            } else {
                $catimage = $dat['upload_data']['file_name'];
            }
            $data = array(            
                'ctg_image' => $catimage,
                'ctg_dated' => time()
            );
            $this->b2bcategory_model->form_insert($data);

        }
    }

php - File uploading error in Codeigniter - Stack Overflow

php codeigniter codeigniter-2 codeigniter-3
Rectangle 27 9

CI is reporting a file type of 'application/zip' which makes sense as the xlsx format is a compressed format (rename it to zip and you can open the contents).

I have added/replaced the following line to the mime types file (application/config/mimes.php):

'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/zip'),

hmmm, it might solved the problem, but it would allow .zip files that are not xlsx files to be uploaded, if i'm not mistaken.

Yeah, I thought that initially, but CI does a check of file extension AND mime type, so if you try and upload a zip file, because the extension is zip and not xlsx it throws an error. I've also added the following lines to the mimes.php file for the work I've been doing: 'slk' => 'text/plain', 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/zip'), 'ods' => 'application/octet-stream

what about a zip file with a xlsx extension (and not a valid xlsx file) ?

This is probably not related to CI at all. I am getting $_FILES['file_browser']['type'] as application/octet-stream when I uploaded a .xlxs file from IE 7 browser. So I added 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/octet-stream') in my code igniter's mime file

php - Upload xls or xlsx files with codeigniter, mime-type error - Sta...

php codeigniter upload mime-types
Rectangle 27 10

enctype="multipart/form-data"

I have enctype="multipart/form-data" already in my form and it still gives the error ?

Unbelievable! This is the only thing (after trying many, many other fixes) that worked!

i got a undefined index error when file upload in php - Stack Overflow

php file upload indexing undefined
Rectangle 27 6

Okay, I found out what was wrong. When choosing "form-data" in PostMan, it automatically sets a header "Content-Type: application/x-www-form-urlencoded".

I just removed the header, and everything worked :)

php - File upload with Laravel through REST - Stack Overflow

php laravel rest api upload
Rectangle 27 3

If you do a print_r on $_FILES, you will see an error code. The meaning of the error code can be found here:

name
file
filename
$_FILES['filename']['tmp_name']

<div id="form"> <form action = "upload.php" method = "post" enctype = 'multipart/form-data'> : <input type="file" name="file" /><br /><br /> <input type="submit" class="button red" value=" " /> </form>

$_FILES['file']['tmp_name']

php file upload strange error - Stack Overflow

php file upload
Rectangle 27 1

Basically you are doing it right. You should never rely on the mime type headers, that are sent from the upload form, because you can fake that easily or it is not present, then you will often get the application/octet-stream header.

So it would be a good way to check if the file extension is matching the allowed mime type for this file extension.

I saw you linked this list here. Its surely a good list, but not really usable for php, because in the array is too much ovverriden, for example:

This will only output two values instead of four, you should use an array like this:

$mimeTypes = array(
    'xlm' => array( 'application/vnd.ms-excel', 'application/x-excel' ),
    'xls' => array( 'application/excel', 'application/vnd.ms-excel' ),
    'txt' => array( 'text/plain' )
);

var_dump( $mimeTypes );

So you can simply check the mimetype with in_array() if you already have the file extension.

This is a basic example you you could solve it. NOTE: This is not a working example, but I think you know where I want to point out:

// you have your file, you said its excel but you uploaded it with extension txt
$filepath = "excel.txt";

if( strpos( $filepath, '.' ) === false ) {
    // no file extension
    // return ?
}
// get the file extension
// well there is surely a better way
$filenameParts = explode( ".", $filepath );
$fileExt = array_pop( $filenameParts );// return the las element of the array and REMOVES it from the array

// your fopen stuff to get the mime type
// ok lets say we are getting back the follwing mime type
$fileMimeType = 'application/vnd.ms-excel';

// now check if filextension is in array and if mimetype for this extension is correct
if( isset( $mimeTypes[$fileExt] ) && in_array( $fileMimeType, $mimeTypes[$fileExt] ) ) {
    // file extension is OK AND mime type matches the file extension
} else {
    // not passed unknown file type, unknown mime type, or someone tricked you
    // your excel.txt should end up here
}

For file size, is it reliable to use mb_strlen on $_FILES? Or only filesize on physical file should be used?

some extensions like .docs .docx .xlsm..... are not listed there. Can you help to add them please?

I made this array pastebin.com/d4ZQBe5A by joining all the following lists + .php extension which is missing in all of them. please contribute to this list to make it as accurate and complete as possible. gist.github.com/plasticbrain/3887245 pastie.org/5668002 pastebin.com/iuTy6K6d total: 1223 extensions as of 16 November 2015

I've updated the answer and added a condtion: strpos( $filepath, '.' ) === false, here you can retur false or whatever, if there is not fileextension, this will also avoid it, if the file itself is named "xls", for the file size I cannot give you a good advice, because I have no clue about file_size security in this context, I always use the filesize from the $_FILES array, had no problem with it

php - How to validate a file type against its extension? - Stack Overf...

php mime-types mime file-type