简体   繁体   中英

Getting Facebook URL shares count returns HTTP/1.1 403 Forbidden on frequently visited site

On one of my PHP sites I use following code to get Facebook share count of each website subpages:

$json_string = file_get_contents('http://graph.facebook.com/?id=' . $url);
$json = json_decode($json_string, true);
if(isset($json['share']['share_count'])){
    return intval( $json['share']['share_count'] );
} else { 
  return 0;
}

The code works fine on a not so much attended website. But when I used that code on a frequently visited site, it gives me zero shares count and following warning:

Warning: Warning (2): file_get_contents( http://graph.facebook.com/?id=.. .): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden

I'm guessing that maybe I call to many requests to the http://graph.facebook.com/?id= URL. My question is how do I solve this problem? I need to update the shares count not less than in 10-15 minutes interval for each subpage. And there are more than 2000 of them. And the users visiting whole website is a huge number.

You really should not call the api for every single page hit, that would definitely hit rate limits. There are 2 things you should do:

  • Create an App and use an App Access Token for every API call: http://www.devils-heaven.com/facebook-access-tokens/
  • Cache the API result and only update it once in a while with a cron job - or on page hit if the last result is older than a specific time range . That would be a better solution if you need to keep the share count up to date. A cron job for 2000 API calls would definitely hit API limits too. Make sure you don´t use all those API calls in a short time, implement some timeout between a batch of API calls.

If that does not work, you need to reduce the amount of API calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM