Search code examples
phpfacebook-graph-apiphp-curlsave-image

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


In my project, when user log in from Facebook, the profile picture will be saved. It is working. But if there is no image, then also a 0 Byte file is saving.

How can I check the url contains image and save only if the image is available

The PHP sample code is given below

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

Solution

  • You can always check curl returned header info with curl_getinfo() (more at php.net)

    So in your case you can curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD) to see how much bytes are returned.

    Also i think facebook should return different HTTP code if no image found, so you can try curl_getinfo($curl, CURLINFO_HTTP_CODE). It should be 200 if image found and 404 if not.