我正在使用file_get_contents()
從遠程服務器上拉出一些圖像,並且我希望在進一步處理之前確認結果字符串是否爲JPG/PNG圖像,例如在本地保存並創建拇指。PHP:如何檢查file_get_contents()的結果字符串是否爲JPG圖像?
$string = file_get_contents($url);
你會怎麼做?
我正在使用file_get_contents()
從遠程服務器上拉出一些圖像,並且我希望在進一步處理之前確認結果字符串是否爲JPG/PNG圖像,例如在本地保存並創建拇指。PHP:如何檢查file_get_contents()的結果字符串是否爲JPG圖像?
$string = file_get_contents($url);
你會怎麼做?
您可以使用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。
PS:PHP_EXIF擴展必須安裝並啓用 – HamZa 2013-03-22 14:11:37
@HamZaDzCyberDeV感謝您的更正,我編輯它,如你所說。 – 2013-03-22 14:14:27
也許非標準PHP函數exif_imagetype()http://www.php.net/manual/en/function.exif-imagetype.php
這是怎麼回事? http://stackoverflow.com/questions/1141227/php-checking-if-the-images-is-jpg – George 2013-03-22 14:11:05