时间:2021-07-01 10:21:17 帮助过:4人阅读
file_get_contents()
之后不用存盘便可以判断文件类型?
- <code class="php">$image=file_get_contents($url);
- file_put_contents($imagePath, $image); //将图片流存入服务器图片目录
- $type=image_type_to_extension(exif_imagetype($imagePath)); //文件类型</code>
我最近采用下边的方式判断:下载文件,得到文件流->存储到硬盘->判断文件类型。
不过觉得这样显得很多余,能不能在file_get_contents()
之后不用存盘便可以判断文件类型?
- <code class="php">$image=file_get_contents($url);
- file_put_contents($imagePath, $image); //将图片流存入服务器图片目录
- $type=image_type_to_extension(exif_imagetype($imagePath)); //文件类型</code>
- <code>$image = file_get_contents($url);
- echo check_image_type($image);
- function check_image_type($image)
- {
- $bits = array(
- 'JPEG' => "\xFF\xD8\xFF",
- 'GIF' => "GIF",
- 'PNG' => "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a",
- 'BMP' => 'BM',
- );
- foreach ($bits as $type => $bit) {
- if (substr($image, 0, strlen($bit)) === $bit) {
- return $type;
- }
- }
- return 'UNKNOWN IMAGE TYPE';
- }</code>
- <code>$finfo = new finfo(FILEINFO_MIME_TYPE);
- var_dump($finfo->file('t.jpg')); // ==> image/jpeg</code>
使用finfo扩展