ファイルのバイナリチェック
バイナリファイルの先頭の数バイトを読むことでmime typeを判別することができる
完璧ではない
magic numberやsignatureと呼ばれる
ファイルアップロード時にファイルチェックを行うときに見るとよい
クライアントサイド
Detect file mime type using magic numbers and JavaScript
JavaScriptでアップロード前にチェックできる
サーバサイド
Rubyで書くイメージ
code:ruby
def png?(file)
signature = file.read(4).chars.map{ _1.ord.to_s(16).upcase }.join
signature.start_with? "89504E47"
end
ローカルで見る時
Vimをhex editorとして使うことで確認もできる
hexdumpも便利
code:shell
$ hexdump test.jpg | head -n 1
0000000 ff d8 ff e1 03 7e 45 78 69 66 00 00 4d 4d 00 2a
参考
https://en.wikipedia.org/wiki/List_of_file_signatures
https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern