Skip to content

Instantly share code, notes, and snippets.

@syamgot
Last active August 3, 2017 08:22
Show Gist options
  • Save syamgot/dc82a3a22fcae82de100fdb20085de58 to your computer and use it in GitHub Desktop.
Save syamgot/dc82a3a22fcae82de100fdb20085de58 to your computer and use it in GitHub Desktop.
[PHP]ネットワーク越しのファイルのmimetypeの取得が失敗したときのメモ

mime_content_typeはローカルにあるファイルはmimetypeを取得できるけど

$file = '100x100.jpg';
echo mime_content_type($file)."\n";
// image/jpeg

ネットワーク越しだと失敗する

$file = 'http://www.placecage.com/100/100';
echo mime_content_type($file)."\n";
// Warning: finfo_file(): Failed identify data 0:(null) in ....

mime_content_type は Fileinfo 関数 に含まれる関数で、Fileinfo はファイルの情報を 推測 する関数らしい。

mime_content_typeの中では概ねこんな感じの処理をしているらしい。

function detect_mimetype ($file) {
	$finfo  = finfo_open(FILEINFO_MIME);
	$result = finfo_file($finfo, $file);
	finfo_close($finfo);
	return $result;
}

ネットワーク越しのファイルだと同じ結果になるけど

$file = 'http://www.placecage.com/100/100';
echo detect_mimetype($file)."\n";
// Warning: finfo_file(): Failed identify data 0:(null) in ....

ローカルのファイルだと mime_content_type と同じ情報が取れる

$file = '100x100.jpg';
echo detect_mimetype($file)."\n";
// image/jpeg; charset=binary

exif関数を使えばネットワーク越しのファイルでも取得できるようだけど、exif情報が含まれていない画像だと検出できないかもしれない?

$file = 'http://www.placecage.com/100/100';
echo image_type_to_mime_type(exif_imagetype($file))."\n";
// image/jpeg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment