File_get_contents, когда URL не существует
Я использую file_get_contents() для доступа к URL-адресу.
file_get_contents('http://somenotrealurl.com/notrealpage');
Если URL-адрес не является реальным, он возвращает это сообщение об ошибке. Как я могу получить это из-за ошибки изящно, чтобы я знал, что страница не существует и действует соответственно без отображения этого сообщения об ошибке?
file_get_contents('http://somenotrealurl.com/notrealpage')
[function.file-get-contents]:
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
in myphppage.php on line 3
Например, в zend вы можете сказать: if ($request->isSuccessful())
$client = New Zend_Http_Client();
$client->setUri('http://someurl.com/somepage');
$request = $client->request();
if ($request->isSuccessful()) {
//do stuff with the result
}
Ответы
Ответ 1
Вам нужно проверить код ответа HTTP:
function get_http_response_code($url) {
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
if(get_http_response_code('http://somenotrealurl.com/notrealpage') != "200"){
echo "error";
}else{
file_get_contents('http://somenotrealurl.com/notrealpage');
}
Ответ 2
С такими командами в PHP вы можете префикс их с помощью @
для подавления таких предупреждений.
@file_get_contents('http://somenotrealurl.com/notrealpage');
file_get_contents() возвращает FALSE
, если происходит сбой, поэтому, если вы проверите возвращенный результат против этого, вы сможете справиться с отказом
$pageDocument = @file_get_contents('http://somenotrealurl.com/notrealpage');
if ($pageDocument === false) {
// Handle error
}
Ответ 3
Каждый раз, когда вы вызываете file_get_contents
с помощью http-оболочки, создается переменная в локальной области: $http_response_header
Эта переменная содержит все заголовки HTTP. Этот метод лучше работает над функцией get_headers()
, так как выполняется только один запрос.
Примечание. 2 разных запроса могут заканчиваться по-другому. Например, get_headers()
вернет 503, а file_get_contents() вернет 200. И вы получите правильный вывод, но не будете использовать его из-за ошибки 503 в вызове get_headers().
function getUrl($url) {
$content = file_get_contents($url);
// you can add some code to extract/parse response number from first header.
// For example from "HTTP/1.1 200 OK" string.
return array(
'headers' => $http_response_header,
'content' => $content
);
}
// Handle 40x and 50x errors
$response = getUrl("http://example.com/secret-message");
if ($response['content'] === FALSE)
echo $response['headers'][0]; // HTTP/1.1 401 Unauthorized
else
echo $response['content'];
Этот aproach также позволяет вам отслеживать несколько заголовков запросов, хранящихся в разных переменных, поскольку, если вы используете file_get_contents() $http_response_header, перезаписывается в локальный охват.
Ответ 4
В то время как file_get_contents
очень точный и удобный, я предпочитаю библиотеку Curl для лучшего контроля. Вот пример.
function fetchUrl($uri) {
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $uri);
curl_setopt($handle, CURLOPT_POST, false);
curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
curl_setopt($handle, CURLOPT_HEADER, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);
$response = curl_exec($handle);
$hlength = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$body = substr($response, $hlength);
// If HTTP response is not 200, throw exception
if ($httpCode != 200) {
throw new Exception($httpCode);
}
return $body;
}
$url = 'http://some.host.com/path/to/doc';
try {
$response = fetchUrl($url);
} catch (Exception $e) {
error_log('Fetch URL failed: ' . $e->getMessage() . ' for ' . $url);
}
Ответ 5
Простой и функциональный (простой в использовании):
function file_contents_exist($url, $response_code = 200)
{
$headers = get_headers($url);
if (substr($headers[0], 9, 3) == $response_code)
{
return TRUE;
}
else
{
return FALSE;
}
}
Пример:
$file_path = 'http://www.google.com';
if(file_contents_exist($file_path))
{
$file = file_get_contents($file_path);
}
Ответ 6
Чтобы избежать двойных запросов, прокомментированных Orbling в ответе ynh, вы можете объединить их ответы. Если вы получите действительный ответ в первую очередь, используйте это. Если не узнать, в чем проблема (при необходимости).
$urlToGet = 'http://somenotrealurl.com/notrealpage';
$pageDocument = @file_get_contents($urlToGet);
if ($pageDocument === false) {
$headers = get_headers($urlToGet);
$responseCode = substr($headers[0], 9, 3);
// Handle errors based on response code
if ($responseCode == '404') {
//do something, page is missing
}
// Etc.
} else {
// Use $pageDocument, echo or whatever you are doing
}
Ответ 7
Вы можете добавить 'ignore_errors' = > true для параметров:
$options = array(
'http' => array(
'ignore_errors' => true,
'header' => "Content-Type: application/json\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents('http://example.com', false, $context);
В этом случае вы сможете прочитать ответ с сервера.
Ответ 8
$url = 'https://www.yourdomain.com';
Нормальный
function checkOnline($url) {
$headers = get_headers($url);
$code = substr($headers[0], 9, 3);
if ($code == 200) {
return true;
}
return false;
}
if (checkOnline($url)) {
// URL is online, do something..
$getURL = file_get_contents($url);
} else {
// URL is offline, throw an error..
}
профессионал
if (substr(get_headers($url)[0], 9, 3) == 200) {
// URL is online, do something..
}
Уровень Wtf
(substr(get_headers($url)[0], 9, 3) == 200) ? echo 'Online' : echo 'Offline';