Reputation: 3880
I am trying to download images from a particular website to my own server
....
public function save_one_img($img_url,$image_filename=false,$save_path)
{
$pathinfo = pathinfo($img_url);
$pic_name=$pathinfo['basename'];
if ($image_filename) $pic_name = $image_filename.'.'.$pathinfo['extension'];
$img_data = @file_get_contents($img_url);
$img_size = file_put_contents($save_path . $pic_name, $img_data);
if ($img_size)
{
echo $img_url . '<span style="color:green;margin-left:80px">success</span><br/>';
} else
{
echo $img_url . '<span style="color:red;margin-left:80px">failed</span><br/>';
}
}
When the image's URL is normal, it works fine. But when it is something like "http://s10.sinaimg.cn/orignal/001MEJWgzy7t10HVWDT39", the code won't be able to get the correct file extension. But when I open the page and right click the image to download it, I can see it is gif
. So in this case, how can I get the extension in my code?
Upvotes: 0
Views: 192
Reputation: 353
You can download the image and use exif_imagetype to detect the image type or you can read the image type in the response header of the remote host(the host that you are getting the image from). In the header there is an attribute called Content-Type and you can get the type of the image there.
Example for exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
Here is an example of header response for a png file.
HTTP/1.1 200 OK
Date: Wed, 15 May 2019 02:42:16 GMT
Server: Apache/2.4.39 (Ubuntu)
Last-Modified: Fri, 22 Mar 2019 17:34:11 GMT
ETag: "19f85-584b2434b434b"
Accept-Ranges: bytes
Content-Length: 106373
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: image/png <---------------
Upvotes: 1