Php curl get status code

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 статус-кодов.

Читайте также:  Sms sending with java

$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 .
Читайте также:  Proxy java net unknownhostexception

Examples

Example #1 curl_getinfo() example

// Create a cURL handle
$ch = curl_init ( ‘http://www.example.com/’ );

// 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/’ );

// 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

    Источник

Оцените статью