以下代码尝试根据访问令牌为Facebook网址运行file_get_contents
:
$access_token=$ret["oauth_token"];
$fbid=$ret["oauth_uid"];
$url ="https://api.facebook.com/method/friends.getAppUsers?format=json&access_token=$access_token";
try {
$content = file_get_contents($url);
if ($content === false) {
$common_friends = array("error_code" => "something");
} else {
$common_friends = json_decode($content,true);
}
} catch (Exception $ex) {
//Who cares
}
所有Facebook设置都是正确的,唯一可能的问题是访问令牌不再有效。在那种情况下,我收到了
的警告file_get_contents():php_network_getaddresses:getaddrinfo失败: 姓名或服务未知
如何升级我的代码,因此如果Facebook用户访问令牌已过期/无效,file_get_contents
将不会发出警告,但会正常失败?
编辑:
$content = @file_get_contents($url);
仍然显示相同的警告,但是,我想摆脱它。 NetBeans还警告我错误控制操作符被滥用。我修改了我的代码如下:
try {
User::checkFacebookToken();
//file_get_contents sends warning message when token does not exist
//the problem is already handled, therefore these warnings are not needed
//this is why we set scream_enabled to false temporarily
ini_set('scream.enabled', false);
$content = file_get_contents($url);
ini_set('scream.enabled', true);
if ($content === false) {
$common_friends = array("error_code" => "something");
} else {
$common_friends = json_decode($content,true);
}
} catch (Exception $ex) {
//Who cares
}
我希望scream.enabled只是暂时改为false。
答案 0 :(得分:1)
解决方案1 :确保不会在主输出上打印警告
只需添加' @ '到' file_get_contents()'自从您通过以下方式正确捕获错误后禁止警告:
error_reporting(E_ERROR | E_PARSE);
if(@file_get_contents() === FALSE) {
// handle this error/warning
}
解决方案2 :在执行请求之前验证您是否拥有有效的Facebook令牌,使用Facebook API
$ch = curl_init();
// you should provide your token
curl_setopt($ch, CURLOPT_URL, "http://graph.facebook.com/me?access_token=52524587821444123");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
$output = json_decode("[" . curl_exec($c) . "]");
if(is_array($output) && isset($output[0]->error)) {
print "Error Message : " . $output[0]->error->message . "<br />";
print "Error Type : " . $output[0]->error->type . "<br />";
print "Error Code : " . $output[0]->error->code . "<br />";
}else {
// do your job with file_get_contents();
}
curl_close($c);
答案 1 :(得分:1)
您可以或者使用cURL,它具有更好的服务器响应处理能力,您可以优雅地显示错误。
$access_token = 'your_access_token';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.facebook.com/method/friends.getAppUsers?format=json&access_token=$access_token");
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($curl);
$response = curl_getinfo($curl);
echo '<pre>';
print_r($response);
if(!curl_errno($curl)){
// Server request success, but check the API returned error code
$content = json_decode($content, true);
print_r($content);
echo $content['error_code'];
echo $content['error_msg'];
}else {
// Server request failure
echo 'Curl error: ' . curl_error($curl);
}
curl_close($curl);