2

So, I've currently used a few different methods to check the mime type. The user uploads a file using a form, I grab the mime type, if it's application/zip, I allow it, if it's anything else, I deny it. The issue is that something (browsers I assume) is changing the mime type to "application/octet-stream"

I'm wondering how else I can verify a file is .zip upon form upload.

Code:

  $name = strtolower(end(explode('.', $filename))); 
    $accepted_types = array('application/zip', 'application/x-zip-compressed',   'multipart/x-zip', 'application/x-compressed'); 

  foreach($accepted_types as $good_type) { 
        if($good_type == $type) {   
            $okay = true;  
            break;
        } else {
            $okay = false;
        }
  }
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
user2376223
  • 21
  • 1
  • 3
  • possible duplicate of [How do I find the mime-type of a file with php?](http://stackoverflow.com/questions/134833/how-do-i-find-the-mime-type-of-a-file-with-php) – BlitZ Aug 01 '13 at 02:24
  • there shouldn't be anything changing the file content-type to application octet-stream in a form post. can you show how your handling the upload please – DevZer0 Aug 01 '13 at 02:25
  • also you can do `in_array($type, $accepted_types);` you don't need a loop. – DevZer0 Aug 01 '13 at 02:27
  • This is not answer question only one hint:you can use this code `$name=strtolower(pathinfo($filename,PATHINFO_EXTENSION));` for get extension file instead `$name = strtolower(end(explode('.', $filename)));` – ops Aug 01 '13 at 02:33

2 Answers2

4

Use mime-content-type.

$type = mime_content_type($filename);
SchizoDuckie
  • 9,353
  • 6
  • 33
  • 40
chris-l
  • 2,802
  • 1
  • 18
  • 18
3

FWIW, you can get the magic bytes using bin2hex. According to Wikipedia (https://en.m.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files), zips have the first 2 hex bytes 50 4B

$zip=file_get_contents("somefile.zip");

echo strtoupper (substr(bin2hex($zip),0,2)); //504B

chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • Reading the whole zip file into memory, just to verify the magic bytes, is wasteful. Also, 4 characters, not 2. `$F=fopen("somefile.zip","r");` `$magic=fread($F,2);` `fclose($F);` `echo strtoupper(substr(bin2hex($magic),0,4)); //504B` – Sinus the Tentacular Jul 11 '19 at 21:01