检查如果图像文件是可用的curl保存facebook个人资料的图像.PHP


Check if image file is available in curl when save facebook profile image. PHP

在我的项目中,当用户从Facebook登录时,会保存头像。它正在起作用。但是如果没有图像,那么也会保存一个0 Byte文件。

如何检查url包含图像并仅在图像可用时保存

PHP示例代码如下

function DownloadImage($url, $dest){
    $curl = curl_init($url);
    $fp = fopen($dest, 'wb');
    curl_setopt($curl, CURLOPT_FILE, $fp);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($curl);   
    curl_close($curl);
    fclose($fp);    
}
try{ 
    $type='large';  
    $social_id='1234';
    DownloadImage('https://graph.facebook.com/'.$social_id.'/picture?type='.$type.'&access_token=[your access token]', $type.'.jpg');

}
catch(Exception $errr){
    echo $errr;
}

你总是可以用curl_getinfo()检查curl返回的头信息(更多在php.net)

因此,在您的情况下,您可以curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD)查看返回多少字节。

我也认为facebook应该返回不同的HTTP代码,如果没有找到图像,所以你可以尝试curl_getinfo($curl, CURLINFO_HTTP_CODE)。如果找到图像,应该是200,如果没有,应该是404