1

I'm trying to get the count for Facebook shares with this function :

<?php

function get_likes($url) {
$json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
$json = json_decode($json_string, true);
return intval( $json[$url]['shares'] );
}

echo get_likes("http://facebook.com");

?>

Sometimes, it's working (I get the good count), but sometimes I get zero share. I didn't manage to identify the reason why (and I tried with tens URL from various websites). Moreover, when I go to this URL http://graph.facebook.com/?ids=http://facebook.com, It always show the right information...

How is it possible to avoid this "zero share" result ?

Gowri
  • 1,832
  • 3
  • 29
  • 53
Guillaume
  • 342
  • 1
  • 9
  • 23

1 Answers1

0

You need to turn on error reporting to see the exact cause for this. Sometimes when you send too much of requests, your requests maybe blocked and your file_get_contents will return FALSE, in that case you will get a 0

Try sending a non-existent value say echo get_likes("1") , You will get the result as 0. If you had turned on the error reporting you will get a warning too.

How do I enable error reporting in PHP?

Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Thank you, here is the warning I got : Warning: file_get_contents(http://graph.facebook.com/?ids=http://facebook.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in /homez.157/frenchpol/www/sharecounter.php on line 20 I read that I should use Curl instead of file_get_contents, but I don't manage to do something that works... – Guillaume Apr 03 '14 at 10:24
  • Yeah, thats what I am talking about.. Do you see 403 ? So seems like they have forbidden the access to your request and that's why you get a 0 as `file_get_contents` failed. – Shankar Narayana Damodaran Apr 03 '14 at 10:26