Следующий код пытается запустить file_get_contents
для URL- file_get_contents
facebook на основе токена доступа:
$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.
В качестве альтернативы вы можете использовать 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);
РЕШЕНИЕ 1: убедитесь, что предупреждения не будут напечатаны на основном выходе
просто добавьте ' @ ' в ' file_get_contents() ', чтобы подавить предупреждение, так как вы правильно оценили ошибку:
error_reporting(E_ERROR | E_PARSE);
if(@file_get_contents() === FALSE) {
// handle this error/warning
}
РЕШЕНИЕ 2: убедитесь, что у вас есть действительный токен Facebook, прежде чем выполнять свой запрос, используя API Facebook
$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);