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
);
}