One way is by using the finfo_buffer
, for example:
if(finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $conteudo) === 'image/jpeg'){
// O $conteudo é um 'image/jpeg'
}
I don’t know how secure this 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 a 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
);
}
I know what the url is but my problem are the ones that don’t end in png,jpg...
– MANIAMAX
For example this is an image and the url has nothing indicating this http://lh3.googleusercontent.com/pMWnZMwH1c6exwP71cqLZ0BYtMSUwIaS-7wwEg9SYLvtRj5PFUlYhXtUvT7goUqeo2UBI29XeU-fFddJmcB1DNe1=s240
– MANIAMAX
It’s true, you’re right
– Miguel