curl_getinfo
Если задана option , возвращает ее значение. В противном случае возвращает ассоциативный массив со следующими элементами (которые соответствуют option ) или false в случае ошибки:
- «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» (устанавливается, только если CURLINFO_HEADER_OUT установлен предыдущим вызовом curl_setopt () )
Changelog
Version | Description |
---|---|
8.0.0 | handle теперь ожидает экземпляр CurlHandle ; ранее ресурс ожидался. |
8.0.0 | option теперь обнуляется; ранее значение по умолчанию было 0 . |
7.3.0 | Введенный 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
Пример # 1 curl_getinfo () Пример
// Create a cURL handle $ch = curl_init('http://www.example.com/'); // Execute curl_exec($ch); // 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); ?>
Пример # 2 Пример использования curl_getinfo () с параметром option
// Create a cURL handle $ch = curl_init('http://www.example.com/'); // Execute curl_exec($ch); // 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:
Информация,собранная этой функцией,сохраняется при повторном использовании рукоятки.Это означает,что если только внутренняя статистика не переопределена этой функцией,возвращается предыдущая информация.
PHP 8.2
(PHP 5 5.5.0,7,8)curl_file_create CURLFile object Эта функция является псевдонимом:CURLFile::__construct()
(PHP 4 4.0.2,5,7,8)curl_init Инициализация сессии Инициализирует новую сессию и возвращает хэндл cURL для использования с curl_setopt(),curl_exec(),curl_close().
(PHP 5,7,8)curl_multi_add_handle normal to Добавляет хэндл к multi multi_handle Хэндл cURL multi,возвращаемый curl_multi_init().
Получаем 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 (! curl_errno ( $ch )) switch ( $http_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE )) case 200 : # OK
break;
default:
echo ‘Неожиданный код HTTP: ‘ , $http_code , «\n» ;
>
>
// Закрываем дескриптор
curl_close ( $ch );
?>
Примечания
Замечание:
Информация, собранная этой функцией, будет сохранена при дальнейшем использовании дескриптора. Это означает, что если статистика не будет перезаписана самой функцией, будет возвращаться информация по предыдущему запросу.
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’ ]];
>
curl_getinfo
CURLINFO_REDIRECT_URL — With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
CURLINFO_PRIMARY_IP — IP address of the most recent connection
CURLINFO_PRIMARY_PORT — Destination port of the most recent connection
CURLINFO_LOCAL_IP — Local (source) IP address of the most recent connection
CURLINFO_LOCAL_PORT — Local (source) port of the most recent connection
CURLINFO_SIZE_UPLOAD — Total number of bytes uploaded
CURLINFO_SIZE_DOWNLOAD — Total number of bytes downloaded
CURLINFO_SPEED_DOWNLOAD — Average download speed
CURLINFO_SPEED_UPLOAD — Average upload speed
CURLINFO_HEADER_SIZE — Total size of all headers received
CURLINFO_HEADER_OUT — The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt
CURLINFO_REQUEST_SIZE — Total size of issued requests, currently only for HTTP requests
CURLINFO_SSL_VERIFYRESULT — Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
CURLINFO_CONTENT_LENGTH_DOWNLOAD — Content length of download, read from Content-Length: field
CURLINFO_CONTENT_LENGTH_UPLOAD — Specified size of upload
CURLINFO_CONTENT_TYPE — Content-Type: of the requested document. NULL indicates server did not send valid Content-Type: header
CURLINFO_PRIVATE — Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of curl_setopt
CURLINFO_RESPONSE_CODE — The last response code
CURLINFO_HTTP_CONNECTCODE — The CONNECT response code
CURLINFO_HTTPAUTH_AVAIL — Bitmask indicating the authentication method(s) available according to the previous response
CURLINFO_PROXYAUTH_AVAIL — Bitmask indicating the proxy authentication method(s) available according to the previous response
CURLINFO_OS_ERRNO — Errno from a connect failure. The number is OS and system specific.
CURLINFO_NUM_CONNECTS — Number of connections curl had to create to achieve the previous transfer
CURLINFO_SSL_ENGINES — OpenSSL crypto-engines supported
CURLINFO_COOKIELIST — All known cookies
CURLINFO_FTP_ENTRY_PATH — Entry path in FTP server
CURLINFO_APPCONNECT_TIME — Time in seconds it took from the start until the SSL/SSH connect/handshake to the remote host was completed
CURLINFO_CERTINFO — TLS certificate chain
CURLINFO_CONDITION_UNMET — Info on unmet time conditional
CURLINFO_RTSP_CLIENT_CSEQ — Next RTSP client CSeq
CURLINFO_RTSP_CSEQ_RECV — Recently received CSeq
CURLINFO_RTSP_SERVER_CSEQ — Next RTSP server CSeq
CURLINFO_RTSP_SESSION_ID — RTSP session ID
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T — The content-length of the download. This is the value read from the Content-Type: field. -1 if the size isn’t known
CURLINFO_CONTENT_LENGTH_UPLOAD_T — The specified size of the upload. -1 if the size isn’t known
CURLINFO_HTTP_VERSION — The version used in the last HTTP connection. The return value will be one of the defined CURL_HTTP_VERSION_* constants or 0 if the version can’t be determined
CURLINFO_PROTOCOL — The protocol used in the last HTTP connection. The returned value will be exactly one of the CURLPROTO_* values
CURLINFO_PROXY_SSL_VERIFYRESULT — The result of the certificate verification that was requested (using the CURLOPT_PROXY_SSL_VERIFYPEER option). Only used for HTTPS proxies
CURLINFO_SCHEME — The URL scheme used for the most recent connection
CURLINFO_SIZE_DOWNLOAD_T — Total number of bytes that were downloaded. The number is only for the latest transfer and will be reset again for each new transfer
CURLINFO_SIZE_UPLOAD_T — Total number of bytes that were uploaded
CURLINFO_SPEED_DOWNLOAD_T — The average download speed in bytes/second that curl measured for the complete download
CURLINFO_SPEED_UPLOAD_T — The average upload speed in bytes/second that curl measured for the complete upload
CURLINFO_APPCONNECT_TIME_T — Time, in microseconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed
CURLINFO_CONNECT_TIME_T — Total time taken, in microseconds, from the start until the connection to the remote host (or proxy) was completed
CURLINFO_FILETIME_T — Remote time of the retrieved document (as Unix timestamp), an alternative to CURLINFO_FILETIME to allow systems with 32 bit long variables to extract dates outside of the 32bit timestamp range
CURLINFO_NAMELOOKUP_TIME_T — Time in microseconds from the start until the name resolving was completed
CURLINFO_PRETRANSFER_TIME_T — Time taken from the start until the file transfer is just about to begin, in microseconds
CURLINFO_REDIRECT_TIME_T — Total time, in microseconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started
CURLINFO_STARTTRANSFER_TIME_T — Time, in microseconds, it took from the start until the first byte is received
CURLINFO_TOTAL_TIME_T — Total time in microseconds for the previous transfer, including name resolving, TCP connect etc.
Return Values
If option is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to option ), or false on failure: