Curl php посмотреть запрос

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().

Источник

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

[Informational 1xx]100=»Continue»
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?

Отправляю данные с помощью curl в сбербанк, он возвращает ошибку.
Как можно посмотреть построенный запрос который я ему отправляю? уже все инфу по CURL прочел, результат можно посмотреть, а вот запрос который отправил нет.

private function gateway($method, $data) < $data['userName'] = $this->user_name; $data['password'] = $this->password; if ($this->test_mode) < $url = self::TEST_URL; >else < $url = self::PROD_URL; >$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => $url . $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($data) ]); $response = curl_exec($curl); $response = json_decode($response, true); curl_close($curl); return $response; >

ThunderCat

а чего там смотреть? Читайте что ошибка от сервиса вам пишет. Ну и данные проверьте, может у вас там везде пусто.

var_dump($url . $method); var_dump(http_build_query($data));

ThunderCat, Хммм, тогда уж лучше error_log($url . $method); , и смотреть в логах HTTP-сервера. Если свой обработчик errorlog-а не всунут.

А то вдруг это в продакшене уже работает, и у одних пользователей (у программистов) всё пучком, а у других пользователей. Как раз в errorlog-е чужое и можно увидеть/отдебажить.

CURLOPT_VERBOSE — true для вывода дополнительной информации. Записывает вывод в поток STDERR, или файл, указанный параметром CURLOPT_STDERR.

Вопрос закрыт для ответов и комментариев

Как настроить прямой доступ к php файлу в .htaccess?

Источник

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:

Источник

Читайте также:  Скрытое поле
Оцените статью