- curl_getinfo
- Notes
- User Contributed Notes 13 notes
- Получаем HTTP статус-коды сайта с помощью PHP и CURL
- PHP – Get HTTP Response Status Code From a URL
- 1. Exploring get_headers function
- 2. Implementation
- 3. Usage
- PHP Function to Get HTTP Response Code (Status) of a URL
- Related Posts
- Как получить HTTP код ответа удаленного веб-сервера из PHP?
- Домен не существует
- Доменные имена с использованием национальных наборов символов.
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 и 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 );
// Идем дальше по списку, чтобы посмотреть, какие мы еще статус коды получили
// Проверяем если урл поменялся или нет
PHP – Get HTTP Response Status Code From a URL
This post shows you how to get the HTTP response status code from a URL. To do this, we will use get_headers built-in function, which returns an array with the headers in the HTTP response.
1. Exploring get_headers function
Let’s create a test to check what response headers we will get.
$url = 'https://bytenota.com'; $responseHeaders = get_headers($url, 1); print_r($responseHeaders);
Array ( [0] => HTTP/1.0 200 OK [Content-Type] => text/html; charset=UTF-8 [Link] => ; rel="https://api.w.org/" [Date] => Tue, 19 Jun 2018 07:42:10 GMT [Accept-Ranges] => bytes [Server] => LiteSpeed [Alt-Svc] => quic=":443"; ma=2592000; v="35,37,38,39" [Connection] => close )
As you can see in the result, the HTTP response status code is in the first index value of the array ( HTTP/1.0 200 OK ).
The response status code can be:
- HTTP/1.0 200 OK:
- HTTP/1.0 301 Moved Permanently
- HTTP/1.0 400 Bad Request
- HTTP/1.0 404 Not Found
- ect.
You can find the full list of response status code on this page.
2. Implementation
function getHTTPResponseStatusCode($url) < $status = null; $headers = @get_headers($url, 1); if (is_array($headers)) < $status = substr($headers[0], 9); >return $status; >
In the above code, we have implemented the function that returns an HTTP response status code only from given URL, i.e. we have removed HTTP/1.0 string in the first index value of the array.
3. Usage
The below are two examples showing how to use the implemented function.
$url = 'https://bytenota.com'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode;
$url = 'https://google.com/this-is-a-test'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode;
PHP Function to Get HTTP Response Code (Status) of a URL
We can use the following PHP function to send a request to the URL and get its HTTP status code.
1 2 3 4 5 6 7 8 9 10 11 12
if (!function_exists("get_http_code")) function get_http_code($url) $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($handle); $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); curl_close($handle); return $httpCode; > > ?>
It is based on the CURL library – which you can install using:
echo get_http_code("https://helloacm.com"); // print 200 ?>
Related Posts
PHP Function to Post to Twitter In order to post twits to Twitter using Twitter APIs, you would first need to…
Steem Reputation Format Function in PHP On Steem Blockchain, the reputation can be formatted in a logarithmetic (base 10) scale. Given…
CloudFlare Blocks Suspicious URL I have set the security level to high and the cloudflare will block suspicious URL,…
How to Mask Email Addresses using PHP Function? For users privacy we don’t want to display the full email addresses — and we…
Filter out Spam Words using PHP Function Many situations we want to be able to detect if a post/comment is spam by…
Left and Right Function in PHP We all know in Visual Basic or VBScript (including VBA i.e. Visual Basic for Application,…
A Simple PHP Function to Disable Google Fonts in WordPress Google Fonts are sometimes heavy-weight and slow to load especially in some regions e.g. mainland…
Simple PHP Function to Display Daily Bing WallPaper Bing uploads a daily wallpaper, and we can show today’s Bing wallpaper via the following…
How to Truncate a String in PHP? The following is a PHP Function that allows us to truncate a string (and optionally…
How to Get Host Root Domain URL in PHP? Suppose you have two or more domains that have image-copies of the same websites, and…
Как получить 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. Качайте архив, распаковывайте и подключайте в ваш код.
Теперь пример выглядит следующим образом: