PHP:如何检查file_get_contents()的结果字符串是否为JPG图像?


PHP: How would you check if the result string of file_get_contents() is a JPG image?

我使用file_get_contents()从远程服务器拉一些图像,我想在进一步处理之前确认结果字符串是否为JPG/PNG图像,如将其保存在本地并创建拇指。

$string = file_get_contents($url);

你会怎么做?

我从这个答案中得到了JPG图像的起始位。所以基本上你能做的就是检查起始位是否相等:

$url = 'https://i.stack.imgur.com/Jh3mC.jpg?s=128&g=1';
$jpg = file_get_contents($url);
if(substr($jpg,0,3) === "'xFF'xD8'xFF"){
    echo "It's a jpg !";
}

可以使用getimagesize()

$url = 'http://www.geenstijl.nl/archives/images/HassVivaCatFight.jpg';
$file = file_get_contents($url);
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, $file);
$size = getimagesize($tmpfname);
if(($size['mime'] == 'image/png') || ($size['mime'] == 'image/jpeg')){
   //do something with the $file
   echo 'yes an jpeg of png';
}
else{
    echo 'Not an jpeg of png ' . $tmpfname .' '. $size['mime']; 
    fclose($handle);
}

我刚刚测试了它,所以它可以工作。您需要制作一个临时文件,因为图像函数与本地数据一起工作,它们只接受本地目录路径,如'C:'wamp2'www'temp'image.png'

如果您不使用fclose($handle);, PHP将在脚本结束后自动删除tmp。

可以使用

exif_imagetype ()

对文件进行评估。请务必查看php手册。

编辑:

请注意必须启用PHP_EXIF。你可以在这里阅读更多信息

可能是标准PHP函数exif_imagetype() http://www.php.net/manual/en/function.exif-imagetype.php