Getting HTTP code in PHP using curl
I’m using CURL to get the status of a site, if it’s up/down or redirecting to another site. I want to get it as streamlined as possible, but it’s not working well.
I have this wrapped in a function. It works fine but performance is not the best because it downloads the whole page, thing in if I remove $output = curl_exec($ch); it returns 0 all the time. Does anyone know how to make the performance better?
8 Answers 8
First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:2+)?(\/.*)?$/i', $url))
Make sure you only fetch the headers, not the body content:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):
$url = 'http://www.example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, true); // we want headers curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo 'HTTP code: ' . $httpcode;
Получаем 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
If option is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to option ), or false on failure:
- «url»
- «content_type»
- «http_code»
- «header_size»
- «request_size»
- «filetime»
- «ssl_verify_result»
- «redirect_count»
- «total_time»
- «namelookup_time»
- «connect_time»
- «pretransfer_time»
- «size_upload»
- «size_download»
- «speed_download»
- «speed_upload»
- «download_content_length»
- «upload_content_length»
- «starttransfer_time»
- «redirect_time»
- «certinfo»
- «primary_ip»
- «primary_port»
- «local_ip»
- «local_port»
- «redirect_url»
- «request_header» (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt() )
Changelog
Version | Description |
---|---|
8.0.0 | handle expects a CurlHandle instance now; previously, a resource was expected. |
8.0.0 | option is nullable now; previously, the default was 0 . |
7.3.0 | Introduced CURLINFO_CONTENT_LENGTH_DOWNLOAD_T , CURLINFO_CONTENT_LENGTH_UPLOAD_T , CURLINFO_HTTP_VERSION , CURLINFO_PROTOCOL , CURLINFO_PROXY_SSL_VERIFYRESULT , CURLINFO_SCHEME , CURLINFO_SIZE_DOWNLOAD_T , CURLINFO_SIZE_UPLOAD_T , CURLINFO_SPEED_DOWNLOAD_T , CURLINFO_SPEED_UPLOAD_T , CURLINFO_APPCONNECT_TIME_T , CURLINFO_CONNECT_TIME_T , CURLINFO_FILETIME_T , CURLINFO_NAMELOOKUP_TIME_T , CURLINFO_PRETRANSFER_TIME_T , CURLINFO_REDIRECT_TIME_T , CURLINFO_STARTTRANSFER_TIME_T , CURLINFO_TOTAL_TIME_T . |
Examples
Example #1 curl_getinfo() example
// Create a cURL handle
$ch = curl_init ( ‘http://www.example.com/’ );
?php
// Check if any error occurred
if (! curl_errno ( $ch )) $info = curl_getinfo ( $ch );
echo ‘Took ‘ , $info [ ‘total_time’ ], ‘ seconds to send a request to ‘ , $info [ ‘url’ ], «\n» ;
>
// Close handle
curl_close ( $ch );
?>
Example #2 curl_getinfo() example with option parameter
// Create a cURL handle
$ch = curl_init ( ‘http://www.example.com/’ );
?php
// 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.
- cURL Functions
- curl_close
- curl_copy_handle
- curl_errno
- curl_error
- curl_escape
- curl_exec
- curl_getinfo
- curl_init
- curl_multi_add_handle
- curl_multi_close
- curl_multi_errno
- curl_multi_exec
- curl_multi_getcontent
- curl_multi_info_read
- curl_multi_init
- curl_multi_remove_handle
- curl_multi_select
- curl_multi_setopt
- curl_multi_strerror
- curl_pause
- curl_reset
- curl_setopt_array
- curl_setopt
- curl_share_close
- curl_share_errno
- curl_share_init
- curl_share_setopt
- curl_share_strerror
- curl_strerror
- curl_unescape
- curl_upkeep
- curl_version