Check is Curl image

2

Is there any way through the Curl request to know if it's an image or not?

$ch = curl_init($image_url);
$name = generateRandomString();
$fp = fopen($caminho.'/'.$name.'.png', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
    
asked by anonymous 21.08.2017 / 19:32

2 answers

4

One way is to use finfo_buffer , for example:

if(finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $conteudo) === 'image/jpeg'){
    // O $conteudo é um 'image/jpeg'
}

I do not know how safe it is. However, the use of this library is recommended in the PHP documentation itself, here :

  

Do not use getimagesize() to check that a given file is a valid image. Use the purpose-built solution such as the Fileinfo extension instead.

In tests, this works as follows:

$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
$conteudo = curl_exec($ch);
curl_close($ch);

if(finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $conteudo) === 'image/jpeg'){
    file_put_contents(
        unpack('H*', random_bytes(32))[1].'.jpg',
        $conteudo
    );
}
    
21.08.2017 / 20:29
4

You can use the curl_getinfo function that will return contentType , from then you can use validation for the image types you need:

 $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
 if($contentType == 'image/png') {
     echo 'Formato válido';
 }
    
21.08.2017 / 19:55