Sunday, May 15, 2011

file_get_contents php method call to facebook loading very slow

when try to get content from an URL, php provide a method "file_get_contents", sometime when you use this method it might takes too long to load.

the following code is used to get the user basic profile from facebook,

$graph_url = "https://graph.facebook.com/me?" . $access_token;
$fbdetail = file_get_contents($graph_url);
$user = json_decode($fbdetail);

for me, file_get_contents takes 5-10 second to load the above code, some say its an DNS issues, below is another function to replace file_get_contenst, it takes less than 3 second for me to load.

just include the below code and replace "file_get_contents" with "get_url"

function get_url($url)
 {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  $tmp = curl_exec($ch);
  curl_close($ch);
  return $tmp;
 }

No comments:

Post a Comment