简体   繁体   中英

Checking “Magic Bytes” or Mime Types in PHP?

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;
        }
  }

使用mime-content-type

$type = mime_content_type($filename);

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

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