- Получаем HTTP статус-коды сайта с помощью PHP и CURL
- curl_getinfo
- Notes
- User Contributed Notes 13 notes
- Как получить HTTP код ответа удаленного веб-сервера из PHP?
- Домен не существует
- Доменные имена с использованием национальных наборов символов.
- PHP: How to get the HTTP status code of a Web page?
- Using fsockopen
- Source code
Получаем HTTP статус-коды сайта с помощью PHP и CURL
Используя нижеприведенный код вы сможете проверить, существует сайт или нет. Также можно проверить, есть ли на сайте редирект. Это может быть полезно для сайтов-каталогов, которые хотите проверить урлы, которые больше не являются активными или обновить свои ссылки. С помощью CURL мы получаем все статус коды для какого либо сайта, а затем ищем совпадения со списком HTTP статус-кодов.
$toCheckURL = «http://google.com» ; // Домен для проверки
curl_setopt( $ch , CURLOPT_URL, $toCheckURL );
curl_setopt( $ch , CURLOPT_HEADER, true);
curl_setopt( $ch , CURLOPT_NOBODY, true);
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION, true);
curl_setopt( $ch , CURLOPT_MAXREDIRS, 10); // разрешаем только 10 редиректов за раз во избежание бесконечного цикла
$http_code = curl_getinfo( $ch , CURLINFO_HTTP_CODE); // Получаем HTTP-код
$new_url = curl_getinfo( $ch , CURLINFO_EFFECTIVE_URL);
// Массив возможных HTTP статус кодовв
$codes = array (0=> ‘Domain Not Found’ ,
203=> ‘Non-Authoritative Information’ ,
407=> ‘Proxy Authentication Required’ ,
413=> ‘Request Entity Too Large’ ,
415=> ‘Unsupported Media Type’ ,
416=> ‘Requested Range Not Satisfiable’ ,
500=> ‘Internal Server Error’ ,
505=> ‘HTTP Version Not Supported’ );
// Ищем совпадения с нашим списком
if (isset( $codes [ $http_code ]))
echo ‘Сайт вернул ответ: ‘ . $http_code . ‘ — ‘ . $codes [ $http_code ]. ‘
‘ ;
preg_match_all( «/HTTP/1.[1|0]s(d)/» , $data , $matches );
// Идем дальше по списку, чтобы посмотреть, какие мы еще статус коды получили
// Проверяем если урл поменялся или нет
curl_getinfo
// Check HTTP status code
if (! curl_errno ( $ch )) switch ( $http_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE )) case 200 : # OK
break;
default:
echo ‘Unexpected HTTP code: ‘ , $http_code , «\n» ;
>
>
// Close handle
curl_close ( $ch );
?>
Notes
Note:
Information gathered by this function is kept if the handle is re-used. This means that unless a statistic is overridden internally by this function, the previous info is returned.
User Contributed Notes 13 notes
Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to ‘http_code’ index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
101=»Switching Protocols» [Successful 2xx]200=»OK»
201=»Created»
202=»Accepted»
203=»Non-Authoritative Information»
204=»No Content»
205=»Reset Content»
206=»Partial Content» [Redirection 3xx]300=»Multiple Choices»
301=»Moved Permanently»
302=»Found»
303=»See Other»
304=»Not Modified»
305=»Use Proxy»
306=»(Unused)»
307=»Temporary Redirect» [Client Error 4xx]400=»Bad Request»
401=»Unauthorized»
402=»Payment Required»
403=»Forbidden»
404=»Not Found»
405=»Method Not Allowed»
406=»Not Acceptable»
407=»Proxy Authentication Required»
408=»Request Timeout»
409=»Conflict»
410=»Gone»
411=»Length Required»
412=»Precondition Failed»
413=»Request Entity Too Large»
414=»Request-URI Too Long»
415=»Unsupported Media Type»
416=»Requested Range Not Satisfiable»
417=»Expectation Failed» [Server Error 5xx]500=»Internal Server Error»
501=»Not Implemented»
502=»Bad Gateway»
503=»Service Unavailable»
504=»Gateway Timeout»
505=»HTTP Version Not Supported»
And an example usage:
$ch = curl_init (); // create cURL handle (ch)
if (! $ch ) die( «Couldn’t initialize a cURL handle» );
>
// set some cURL options
$ret = curl_setopt ( $ch , CURLOPT_URL , «http://mail.yahoo.com» );
$ret = curl_setopt ( $ch , CURLOPT_HEADER , 1 );
$ret = curl_setopt ( $ch , CURLOPT_FOLLOWLOCATION , 1 );
$ret = curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 0 );
$ret = curl_setopt ( $ch , CURLOPT_TIMEOUT , 30 );
// execute
$ret = curl_exec ( $ch );
if (empty( $ret )) // some kind of an error happened
die( curl_error ( $ch ));
curl_close ( $ch ); // close cURL handler
> else $info = curl_getinfo ( $ch );
curl_close ( $ch ); // close cURL handler
if (empty( $info [ ‘http_code’ ])) die( «No HTTP code was returned» );
> else // load the HTTP codes
$http_codes = parse_ini_file ( «path/to/the/ini/file/I/pasted/above» );
// echo results
echo «The server responded:
» ;
echo $info [ ‘http_code’ ] . » » . $http_codes [ $info [ ‘http_code’ ]];
>
Как получить HTTP код ответа удаленного веб-сервера из PHP?
Когда требуется получить HTTP код для заданной URL, то вы наверняка воспользуетесь PHP функцией get_headers($url). Дальше я расскажу о разных подводных камнях и возникающих попутных проблемах.
В первом приближении задача решается элементарно. У вас есть URL, вы запрашиваете только заголовки, т.к. вам не нужен сам документ. В заголовках можно найти и пропарсить стандартный ответ сервера, чтобы извлечь код ответа.
Скорее всего, вы действительно получите желаемое, но не всегда. Потому перейдем к рассмотрению наиболее частых коллизий.
Домен не существует
Да такое бывает, когда введенный адрес не существует. Вернее не адрес, а доменное имя сайта. Запрос посылать некуда, а вы увидите (если не отключили вывод php warnings) что то вроде следующего:
PHP вернет пустые заголовки, из которых ничего не извлечь. Как можно обработать эту ситуацию?
Тут вы уже не увидите сообщений от PHP, а в случае невозможности определить адрес сервера — будет установлено какое то кастомное значение вместо HTTP кода, чтобы иметь возможность его обработать дальше.
Доменные имена с использованием национальных наборов символов.
Функция get_headers не настолько умна, чтобы переводить ваш http://россия.рф в http://xn--h1alffa9f.xn--p1ai200.
Если вы попытаетесь запросить заголовки без перевода в нужный вид, то прошлый пример выдаст вам загадочное ‘no response’. В то время как браузер без проблем откроет сайт, т.к. умеет переводить доменные имена, в которых используются местные национальные наборы символов, отличные от латиницы.
Для конвертации используем свободно распространяемую библиотеку idna_convert. Качайте архив, распаковывайте и подключайте в ваш код.
Теперь пример выглядит следующим образом:
PHP: How to get the HTTP status code of a Web page?
How when you want to access remotely by a script, the pages of a site, to know whether a page exists, it is a redirection, or if a link is broken? This issue is essential for writing a script for the Web. Here is a function to get this status code based on a PHP function, fsockopen, compatible with current versions of PHP. A script is provided to demonstrate the use, that meets the strict rules of this function.
Using fsockopen
We use the function with two parameters:
— The URL of the site, without filename, for example: www.scriptol.com.
— A file name, possibly with a directory. The domain is passed as a parameter when calling the function.
$server = "www.example.com" $fp=fsockopen($server,80,$errno,$errstr,30);
Without protocol added, the function uses the TCP default. It could be specified explicitly: tcp://www.scriptol.com or udp://www.scriptol.com. The second parameter is the port, usually 80, the next two are used to retrieve the number and the error when it occurs. The latter is the maximum waiting time granted to get a response in milliseconds. Once the connection opened, we send the request. It is in our case to access a file, hence the GET command:
$page = "index.php" $out="GET /$page HTTP/1.1\r\n"; $out.="Host: $server\r\n"; $out.="Connection: Close\r\n\r\n"; fwrite($fp,$out);
It specifies the page, the server and it closes the connection. But the file is obtained and the HTTP header too. To retrieve these data, the fgets function is used:
HTTP/1.1 301 Moved Permanently
While the code 404 indicates that the page does not exist. We can now extract the code with the substr function as it is done in the script given below.