I recently used the following method to judge: download the file, get the file stream->store to the hard disk->determine the file type.
But I think this seems redundant. Can I determine the file type without saving after 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>
I recently used the following method to judge: download the file, get the file stream->store to the hard disk->determine the file type.
But I think this seems redundant. Can I determine the file type without saving after 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>
Use finfo extension