John
John

Reputation: 13

save facebook image using curl, file_get_contents, fopen/fread/fwrite, copy - strange headers

I'm trying to save images from facebook and have a problem.

It works well except images from domain external.ak.fbcdn.net

i.e. http://external.ak.fbcdn.net/safe_image.php?d=85623fa1fc7679d3e4e5e9ab3b9ad426&w=50&h=50&url=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F3%2F38%2FTwo_dancers.jpg&crop

Using curl, file_get_contents, fopen/fread/fwrite, copy return 1x1 gif instead of actual image.

I coudn't find solution so I checked headers on url posted above (get_headers) and get that gif:

array(10) {
  [0]=>
  string(15) "HTTP/1.0 200 OK"
  ["Content-Type"]=>
  string(9) "image/gif"
  ["Pragma"]=>
  string(8) "no-cache"
  ["X-FB-Debug"]=>
  string(44) "qcXPNe3kW3TLOCgBRQQUBr/ekWiKISQTqbdUbDi7vXs="
  ["X-Cnection"]=>
  string(5) "close"
  ["Content-Length"]=>
  string(2) "43"
  ["Cache-Control"]=>
  string(44) "private, no-cache, no-store, must-revalidate"
  ["Expires"]=>
  string(29) "Sat, 31 Mar 2012 20:52:23 GMT"
  ["Date"]=>
  string(29) "Sat, 31 Mar 2012 20:52:23 GMT"
  ["Connection"]=>
  string(5) "close"
}    

Can someone please help me with this ? Is it some kind of facebook protection or I'm doing something wrong?

Just in case here is my curl code:

$ch = curl_init( $url );
$fp = fopen( $filePath, 'wb');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);

Upvotes: 1

Views: 2134

Answers (1)

Juicy Scripter
Juicy Scripter

Reputation: 25918

For URL's that prefixed with .../safe_image.php you'll need to extract real URL of the image :

$url = 'http://external.ak.fbcdn.net/safe_image.php?d=85623fa1fc7679d3e4e5e9ab3b9ad426&w=50&h=50&url=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F3%2F38%2FTwo_dancers.jpg&crop';
$parts = parse_url($url);
parse_str($parts['query'], $params);
$realUrl = $params['url'];
print_r($realUrl);
// http://upload.wikimedia.org/wikipedia/commons/3/38/Two_dancers.jpg

Upvotes: 2

Related Questions