Unable to file_get_contents to work
I am using facebook graph api, to retrieve logged in user's info.
$facebookdata = 开发者_开发百科json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' . $fb_accesstoken . '&fields=name,picture'),true);
Now When I var_dump I get null. I did try to goto url https://graph.facebook.com/me?access_token=ACCESS_TOKEN&fields=id,name,picture. It shows the name and photourl.
I appreciate any help.
Instead of using file_get_contents
you can you the Facebook PHP SDK (see on github) which is easier to use :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
$args['fields'] = "name,picture";
$facebookdata = $facebook->api('/me', $args);
Check the example of the SDK out (well documented) if you want to see the flow to get the user access token.
Hope that helps !
Check if allow_url_fopen
is enabled in your php.ini
. Otherwise adapt, because file_get_contents will not be able to read from http URLs then.
Second, raise your error_reporting
level. It should have told you so.
If you get no error message, then access with the PHP user_agent
might be blocked. There is another php.ini setting for that. Also alternatively, just try curl
.
You should determine what http response code is being returned by your request.
I've found that file_get_contents() only works when the http response is 200, OK.
It doesn't return a string if the response code is 404 (page not found), 400 (bad request), etc.
Hitting the Facebook API with an incorrect access_token returns 400.
Example:
file_get_contents() with 'http://www.google.co.uk' works, http response from google is 200
file_get_contents() with 'http://www.google.co.uk/me' is null, http response from google is 404
//i had the same problem before.for some reason the server has a problem with file_get_contents and i used this function.try it instead
/* gets the data from a URL */
function get_myurl_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'https://graph.facebook.com/me?access_token=' . $fb_accesstoken . '&fields=name,picture';
$facebookdata = json_decode(get_myurl_data($url));
精彩评论