Question

help me to fix this problem I want to download Facebook user image profile using PHP 5.3.27 I use this code, the image is downloaded but size 0 bytes and cannot be open.

first code:

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_exec($curl);   
    curl_close($curl);
    fclose($fp);    
}

try{   
    $social_id='1234';
    DownloadImage('http://graph.facebook.com/'.$social_id.'/picture', '../user_image/normal/'.$social_id.'.jpg');
    DownloadImage('http://graph.facebook.com/'.$social_id.'/picture?width=141&height=141', '../user_image/bigger/'.$social_id.'.jpg');  

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

and this is the second code.. with the same result (0 bytes of size and cannot be open)

$url = 'http://graph.facebook.com/1234/picture';
$img = '../user_image/bigger/1234.jpg';
file_put_contents($img, file_get_contents($url));
Was it helpful?

Solution

As I see

http://graph.facebook.com/1234/picture

do redirect to:

https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/t1.0-1/c47.7.85.85/s50x50/417599_10100236041078581_1583446385_a.jpg

Try to add: curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).

So your code may looks like:

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{   
    $social_id='1234';
    DownloadImage('http://graph.facebook.com/'.$social_id.'/picture', '../user_image/normal/'.$social_id.'.jpg');
    DownloadImage('http://graph.facebook.com/'.$social_id.'/picture?width=141&height=141', '../user_image/bigger/'.$social_id.'.jpg');  

}
catch(Exception $errr){
    echo $errr;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top