Как найти ошибки curl

you can generate curl error after its execution

$url = 'http://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

and here are curl error code

if someone need more information about curl errors

<?php

    $error_codes=array(
    [1] => 'CURLE_UNSUPPORTED_PROTOCOL',
    [2] => 'CURLE_FAILED_INIT',
    [3] => 'CURLE_URL_MALFORMAT',
    [4] => 'CURLE_URL_MALFORMAT_USER',
    [5] => 'CURLE_COULDNT_RESOLVE_PROXY',
    [6] => 'CURLE_COULDNT_RESOLVE_HOST',
    [7] => 'CURLE_COULDNT_CONNECT',
    [8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
    [9] => 'CURLE_REMOTE_ACCESS_DENIED',
    [11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
    [13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
    [14]=>'CURLE_FTP_WEIRD_227_FORMAT',
    [15] => 'CURLE_FTP_CANT_GET_HOST',
    [17] => 'CURLE_FTP_COULDNT_SET_TYPE',
    [18] => 'CURLE_PARTIAL_FILE',
    [19] => 'CURLE_FTP_COULDNT_RETR_FILE',
    [21] => 'CURLE_QUOTE_ERROR',
    [22] => 'CURLE_HTTP_RETURNED_ERROR',
    [23] => 'CURLE_WRITE_ERROR',
    [25] => 'CURLE_UPLOAD_FAILED',
    [26] => 'CURLE_READ_ERROR',
    [27] => 'CURLE_OUT_OF_MEMORY',
    [28] => 'CURLE_OPERATION_TIMEDOUT',
    [30] => 'CURLE_FTP_PORT_FAILED',
    [31] => 'CURLE_FTP_COULDNT_USE_REST',
    [33] => 'CURLE_RANGE_ERROR',
    [34] => 'CURLE_HTTP_POST_ERROR',
    [35] => 'CURLE_SSL_CONNECT_ERROR',
    [36] => 'CURLE_BAD_DOWNLOAD_RESUME',
    [37] => 'CURLE_FILE_COULDNT_READ_FILE',
    [38] => 'CURLE_LDAP_CANNOT_BIND',
    [39] => 'CURLE_LDAP_SEARCH_FAILED',
    [41] => 'CURLE_FUNCTION_NOT_FOUND',
    [42] => 'CURLE_ABORTED_BY_CALLBACK',
    [43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
    [45] => 'CURLE_INTERFACE_FAILED',
    [47] => 'CURLE_TOO_MANY_REDIRECTS',
    [48] => 'CURLE_UNKNOWN_TELNET_OPTION',
    [49] => 'CURLE_TELNET_OPTION_SYNTAX',
    [51] => 'CURLE_PEER_FAILED_VERIFICATION',
    [52] => 'CURLE_GOT_NOTHING',
    [53] => 'CURLE_SSL_ENGINE_NOTFOUND',
    [54] => 'CURLE_SSL_ENGINE_SETFAILED',
    [55] => 'CURLE_SEND_ERROR',
    [56] => 'CURLE_RECV_ERROR',
    [58] => 'CURLE_SSL_CERTPROBLEM',
    [59] => 'CURLE_SSL_CIPHER',
    [60] => 'CURLE_SSL_CACERT',
    [61] => 'CURLE_BAD_CONTENT_ENCODING',
    [62] => 'CURLE_LDAP_INVALID_URL',
    [63] => 'CURLE_FILESIZE_EXCEEDED',
    [64] => 'CURLE_USE_SSL_FAILED',
    [65] => 'CURLE_SEND_FAIL_REWIND',
    [66] => 'CURLE_SSL_ENGINE_INITFAILED',
    [67] => 'CURLE_LOGIN_DENIED',
    [68] => 'CURLE_TFTP_NOTFOUND',
    [69] => 'CURLE_TFTP_PERM',
    [70] => 'CURLE_REMOTE_DISK_FULL',
    [71] => 'CURLE_TFTP_ILLEGAL',
    [72] => 'CURLE_TFTP_UNKNOWNID',
    [73] => 'CURLE_REMOTE_FILE_EXISTS',
    [74] => 'CURLE_TFTP_NOSUCHUSER',
    [75] => 'CURLE_CONV_FAILED',
    [76] => 'CURLE_CONV_REQD',
    [77] => 'CURLE_SSL_CACERT_BADFILE',
    [78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
    [79] => 'CURLE_SSH',
    [80] => 'CURLE_SSL_SHUTDOWN_FAILED',
    [81] => 'CURLE_AGAIN',
    [82] => 'CURLE_SSL_CRL_BADFILE',
    [83] => 'CURLE_SSL_ISSUER_ERROR',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [85] => 'CURLE_RTSP_CSEQ_ERROR',
    [86] => 'CURLE_RTSP_SESSION_ERROR',
    [87] => 'CURLE_FTP_BAD_FILE_LIST',
    [88] => 'CURLE_CHUNK_FAILED');

    ?>

Я использую функции PHP curl для отправки данных на веб-сервер с моей локальной машины. Мой код выглядит следующим образом:

$c = curl_init();

curl_setopt($c, CURLOPT_URL, $url);

curl_setopt($c, CURLOPT_RETURNTRANSFER, true);

curl_setopt($c, CURLOPT_POST, true);

curl_setopt($c, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($c);

if (curl_exec($c) === false) {

    echo “ok”;

} else {

    echo “error”;

}

curl_close($c);

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

Ответ 1

Вы можете использовать функцию curl_error(), чтобы определить, произошла ли какая-то ошибка. Например:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $your_url);

curl_setopt($ch, CURLOPT_FAILONERROR, true); // Требуется для того, чтобы коды ошибок HTTP сообщались через наш вызов к curl_error($ch)

//…

curl_exec($ch);

if (curl_errno($ch)) {

    $error_msg = curl_error($ch);

}

curl_close($ch);

if (isset($error_msg)) {

    // TODO – Обработать ошибку cURL соответствующим образом

}

Ответ 2

Если CURLOPT_FAILONERROR равно false, ошибки http не будут вызывать ошибок curl.

<?php

if (@$_GET[‘curl’]==”yes”) {

  header(‘HTTP/1.1 503 Service Temporarily Unavailable’);

} else {

  $ch=curl_init($url = “http://”.$_SERVER[‘SERVER_NAME’].$_SERVER[‘PHP_SELF’].”?curl=yes”);

  curl_setopt($ch, CURLOPT_FAILONERROR, true);

  $response=curl_exec($ch);

  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

  $curl_errno= curl_errno($ch);

  if ($http_status==503)

    echo “HTTP Status == 503 <br/>”;

  echo “Curl Errno returned $curl_errno <br/>”;

}

Ответ 3

Вы можете сгенерировать ошибку curl после его выполнения:

$url = ‘http://example.com’;

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

if(curl_errno($ch)){

    echo ‘Request Error:’ . curl_error($ch);

}

 И вот коды ошибок curl:

если кому-то нужна дополнительная информация об ошибках curl

<?php

    $error_codes=array(

    [1] => ‘CURLE_UNSUPPORTED_PROTOCOL’,

    [2] => ‘CURLE_FAILED_INIT’,

    [3] => ‘CURLE_URL_MALFORMAT’,

    [4] => ‘CURLE_URL_MALFORMAT_USER’,

    [5] => ‘CURLE_COULDNT_RESOLVE_PROXY’,

    [6] => ‘CURLE_COULDNT_RESOLVE_HOST’,

    [7] => ‘CURLE_COULDNT_CONNECT’,

    [8] => ‘CURLE_FTP_WEIRD_SERVER_REPLY’,

    [9] => ‘CURLE_REMOTE_ACCESS_DENIED’,

    [11] => ‘CURLE_FTP_WEIRD_PASS_REPLY’,

    [13] => ‘CURLE_FTP_WEIRD_PASV_REPLY’,

    [14]=>’CURLE_FTP_WEIRD_227_FORMAT’,

    [15] => ‘CURLE_FTP_CANT_GET_HOST’,

    [17] => ‘CURLE_FTP_COULDNT_SET_TYPE’,

    [18] => ‘CURLE_PARTIAL_FILE’,

    [19] => ‘CURLE_FTP_COULDNT_RETR_FILE’,

    [21] => ‘CURLE_QUOTE_ERROR’,

    [22] => ‘CURLE_HTTP_RETURNED_ERROR’,

    [23] => ‘CURLE_WRITE_ERROR’,

    [25] => ‘CURLE_UPLOAD_FAILED’,

    [26] => ‘CURLE_READ_ERROR’,

    [27] => ‘CURLE_OUT_OF_MEMORY’,

    [28] => ‘CURLE_OPERATION_TIMEDOUT’,

    [30] => ‘CURLE_FTP_PORT_FAILED’,

    [31] => ‘CURLE_FTP_COULDNT_USE_REST’,

    [33] => ‘CURLE_RANGE_ERROR’,

    [34] => ‘CURLE_HTTP_POST_ERROR’,

    [35] => ‘CURLE_SSL_CONNECT_ERROR’,

    [36] => ‘CURLE_BAD_DOWNLOAD_RESUME’,

    [37] => ‘CURLE_FILE_COULDNT_READ_FILE’,

    [38] => ‘CURLE_LDAP_CANNOT_BIND’,

    [39] => ‘CURLE_LDAP_SEARCH_FAILED’,

    [41] => ‘CURLE_FUNCTION_NOT_FOUND’,

    [42] => ‘CURLE_ABORTED_BY_CALLBACK’,

    [43] => ‘CURLE_BAD_FUNCTION_ARGUMENT’,

    [45] => ‘CURLE_INTERFACE_FAILED’,

    [47] => ‘CURLE_TOO_MANY_REDIRECTS’,

    [48] => ‘CURLE_UNKNOWN_TELNET_OPTION’,

    [49] => ‘CURLE_TELNET_OPTION_SYNTAX’,

    [51] => ‘CURLE_PEER_FAILED_VERIFICATION’,

    [52] => ‘CURLE_GOT_NOTHING’,

    [53] => ‘CURLE_SSL_ENGINE_NOTFOUND’,

    [54] => ‘CURLE_SSL_ENGINE_SETFAILED’,

    [55] => ‘CURLE_SEND_ERROR’,

    [56] => ‘CURLE_RECV_ERROR’,

    [58] => ‘CURLE_SSL_CERTPROBLEM’,

    [59] => ‘CURLE_SSL_CIPHER’,

    [60] => ‘CURLE_SSL_CACERT’,

    [61] => ‘CURLE_BAD_CONTENT_ENCODING’,

    [62] => ‘CURLE_LDAP_INVALID_URL’,

    [63] => ‘CURLE_FILESIZE_EXCEEDED’,

    [64] => ‘CURLE_USE_SSL_FAILED’,

    [65] => ‘CURLE_SEND_FAIL_REWIND’,

    [66] => ‘CURLE_SSL_ENGINE_INITFAILED’,

    [67] => ‘CURLE_LOGIN_DENIED’,

    [68] => ‘CURLE_TFTP_NOTFOUND’,

    [69] => ‘CURLE_TFTP_PERM’,

    [70] => ‘CURLE_REMOTE_DISK_FULL’,

    [71] => ‘CURLE_TFTP_ILLEGAL’,

    [72] => ‘CURLE_TFTP_UNKNOWNID’,

    [73] => ‘CURLE_REMOTE_FILE_EXISTS’,

    [74] => ‘CURLE_TFTP_NOSUCHUSER’,

    [75] => ‘CURLE_CONV_FAILED’,

    [76] => ‘CURLE_CONV_REQD’,

    [77] => ‘CURLE_SSL_CACERT_BADFILE’,

    [78] => ‘CURLE_REMOTE_FILE_NOT_FOUND’,

    [79] => ‘CURLE_SSH’,

    [80] => ‘CURLE_SSL_SHUTDOWN_FAILED’,

    [81] => ‘CURLE_AGAIN’,

    [82] => ‘CURLE_SSL_CRL_BADFILE’,

    [83] => ‘CURLE_SSL_ISSUER_ERROR’,

    [84] => ‘CURLE_FTP_PRET_FAILED’,

    [84] => ‘CURLE_FTP_PRET_FAILED’,

    [85] => ‘CURLE_RTSP_CSEQ_ERROR’,

    [86] => ‘CURLE_RTSP_SESSION_ERROR’,

    [87] => ‘CURLE_FTP_BAD_FILE_LIST’,

    [88] => ‘CURLE_CHUNK_FAILED’);

    ?>

Ответ 4

Поскольку вы заинтересованы в отлове ошибок, связанных с сетью, и ошибок HTTP, ниже приведен лучший подход:

function curl_error_test($url) {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $responseBody = curl_exec($ch);

    /*

     * if curl_exec failed then

     * $responseBody равно false

     * curl_errno() возвращает ненулевое число

     * curl_error() возвращает непустую строку

     * Какой из них использовать – решать вам

     */

    if ($responseBody === false) {

        return “CURL Error: ” . curl_error($ch);

    }

    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    /*

     * 4xx коды состояния – ошибки клиента

     * 5xx коды состояния – ошибки сервера

     */

    if ($responseCode >= 400) {

        return “HTTP Error: ” . $responseCode;

    }

    return “Нет ошибки CURL или HTTP “;

}

 Тесты:

curl_error_test(“http://expamle.com”);          //  Ошибка CURL : Невозможно определить хост : expamle.com

curl_error_test(“http://example.com/whatever”); // Ошибка HTTP: 404

curl_error_test(“http://example.com”);          // Все в порядке с CURL или HTTP

Ответ 5

Еще один вариант кода:

  $responseInfo = curl_getinfo($ch);

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

    $body = substr($response, $header_size);

    $result=array();

    $result[‘httpCode’]=$httpCode;

    $result[‘body’]=json_decode($body);

    $result[‘responseInfo’]=$responseInfo;

    print_r($httpCode); 

     print_r($result[‘body’]); exit;

    curl_close($ch);

    if($httpCode == 403) {

        print_r(“Доступ запрещен”);

        exit;

    }   else {

         // другие ошибки 

     }

I’m using curl at the command line on Linux to issue HTTP requests. The response bodies are printed to standard out, which is fine, but I can’t see from the man page how to get curl to print the HTTP status code from the response (404, 403 etc). Is this possible?

asked Apr 18, 2011 at 10:28

kdt's user avatar

4

This should work for you if the web server is able to respond to HEAD requests (this will not perform a GET request):

curl -I http://www.example.org

As an addition, to let cURL follow redirects (3xx statuses) add -L.

Wouter's user avatar

Wouter

1291 silver badge7 bronze badges

answered Apr 18, 2011 at 10:56

pberlijn's user avatar

pberlijnpberlijn

9,4241 gold badge15 silver badges8 bronze badges

12

A more specific way to print out just the HTTP status code is something along the lines of:

curl -s -o /dev/null -w "%{http_code}" http://www.example.org/

A lot easier to work with in scripts, as it doesn’t require any parsing 🙂

The parameter -I might be added to improve response load performance. This will change the call to a HEAD call which will fetch response overhead only, without the body.

Note: %{http_code} returns on first line of HTTP payload (available variables for the -w option on the curl documentation page)

i.e.:

curl -s -o /dev/null -I -w "%{http_code}" http://www.example.org/

Nate Anderson's user avatar

answered Jun 28, 2012 at 0:25

pvandenberk's user avatar

pvandenberkpvandenberk

13.9k2 gold badges13 silver badges3 bronze badges

21

You can print the status code, in addition to all the headers by doing the following:

curl -i http://example.org

The good thing about -i is that it works with -X POST as well.

answered Dec 4, 2012 at 20:45

Cyril David's user avatar

Cyril DavidCyril David

4,6571 gold badge12 silver badges2 bronze badges

7

If you want to see the header as well as the result you can use the verbose option:

curl -v http://www.example.org
curl --verbose http://www.example.org

The status will appear in the header. E.g.

< Date: Tue, 04 Nov 2014 19:12:59 GMT
< Content-Type: application/json; charset=utf-8
< Status: 422 Unprocessable Entity

Dennis's user avatar

Dennis

4525 silver badges14 bronze badges

answered May 3, 2012 at 4:28

Enrico Susatyo's user avatar

Enrico SusatyoEnrico Susatyo

3,4762 gold badges18 silver badges20 bronze badges

4

If you want to capture the HTTP status code in a variable, but still redirect the content to STDOUT, you must create two STDOUTs. You can do so with process substitution >() and command substitution $().

First, create a file descriptor 3 for your current process’ STDOUT with exec 3>&1.

Then, use curl’s -o option to redirect the response content to a temporary fifo using command substitution, and then within that command substitution, redirect output back to your current process STDOUT file descriptor 3 with -o >(cat >&3).

Putting it all together in bash 3.2.57(1)-release (standard for macOS):

# creates a new file descriptor 3 that redirects to 1 (STDOUT)
exec 3>&1 
# Run curl in a separate command, capturing output of -w "%{http_code}" into HTTP_STATUS
# and sending the content to this command's STDOUT with -o >(cat >&3)
HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.com')

Note that this doesn’t work in /bin/sh as SamK noted in the comments below.

answered Jan 8, 2015 at 20:59

Heath Borders's user avatar

8

Redefine curl output:

curl -sw '%{http_code}' http://example.org

Can be used with any request type.

answered Aug 5, 2014 at 18:18

Grzegorz Luczywo's user avatar

2

Status code ONLY

[0]$ curl -LI http://www.example.org -o /dev/null -w '%{http_code}n' -s
[0]$ 200

All credit to this GIST

answered Feb 8, 2017 at 10:44

mahatmanich's user avatar

mahatmanichmahatmanich

6455 silver badges7 bronze badges

2

This is a painful curl --fail limitation. From man curl :

-f, –fail
(HTTP) Fail silently (no output at all) on server errors

But there is no way to get both the non-zero return code AND the response body in stdout.

Based on pvandenberk’s answer and this other very useful trick learned on SO, here is a workaround :

curl_with_error_code () {
    _curl_with_error_code "$@" | sed '$d'
}
_curl_with_error_code () {
    local curl_error_code http_code
    exec 17>&1
    http_code=$(curl --write-out 'n%{http_code}n' "$@" | tee /dev/fd/17 | tail -n 1)
    curl_error_code=$?
    exec 17>&-
    if [ $curl_error_code -ne 0 ]; then
        return $curl_error_code
    fi
    if [ $http_code -ge 400 ] && [ $http_code -lt 600 ]; then
        echo "HTTP $http_code" >&2
        return 127
    fi
}

This function behaves exactly as curl, but will return 127 (a return code non-used by curl) in case of a HTTP code in the range [400, 600[.

Community's user avatar

answered Apr 6, 2016 at 13:08

Lucas Cimon's user avatar

Lucas CimonLucas Cimon

4824 silver badges11 bronze badges

3

This will send a request to url, get only the first line of the response, split it on blocks and select the second one.

It contains the response code

curl -I http://example.org 2>/dev/null | head -n 1 | cut -d$' ' -f2

OneCricketeer's user avatar

answered Jul 15, 2015 at 20:08

Filip Spiridonov's user avatar

2

For a POST request, the following worked:

curl -w 'RESP_CODE:%{response_code}' -s -X POST --data '{"asda":"asd"}' http://example.com --header "Content-Type:application/json"|grep -o  'RESP_CODE:[1-4][0-9][0-9]'

answered Jan 7, 2016 at 8:36

zafar142003's user avatar

zafar142003zafar142003

2512 silver badges4 bronze badges

Use the following cURL command and pipe it to grep like so:

$ curl -I -s -L http://example.com/v3/get_list | grep “HTTP/1.1”

Here’s what each flag does:

  • -I: Show only response headers
  • -s: Silent – Don’t show progress bar
  • -L: Follow Location: headers

Here is a link to HTTP status codes.

Run from the command line. This curl runs in silent mode, follows any redirects, get the HTTP headers. grep will print the HTTP status code to standard output.

Cas's user avatar

Cas

1,9242 gold badges18 silver badges42 bronze badges

answered Nov 21, 2016 at 11:28

Savitoj Singh's user avatar

Here is some curl command that is using GET and that returns the HTTP code.

curl -so /dev/null -w '%{response_code}' http://www.example.org

Please remember that the approach below is using HEAD, which is faster but it may not work well with some web less compliant HTTP servers.

 curl -I http://www.example.org

answered Jun 23, 2016 at 10:37

sorin's user avatar

sorinsorin

11.5k20 gold badges62 silver badges73 bronze badges

2

curl -so -i /dev/null -w "%{http_code}"  http://www.any_example.com

This will return the following information:

  1. response data, if any data is returned by API like error
  2. status code

answered Mar 8, 2017 at 5:12

srana's user avatar

sranasrana

611 silver badge2 bronze badges

2

An example of how to use the response codes. I use this to re-download Geolite databases only if they have changed (-z) & also following redirects (-L):

url=http://example.com/file.gz
file=$(basename $url)

response=$(curl -L -s -o $file -z $file $url -w "%{http_code}")

case "$response" in
        200) do_something ;;
        301) do_something ;;
        304) printf "Received: HTTP $response (file unchanged) ==> $urln" ;;
        404) printf "Received: HTTP $response (file not found) ==> $urln" ;;
          *) printf "Received: HTTP $response ==> $urln" ;;
esac

answered Apr 1, 2018 at 17:21

Stuart Cardall's user avatar

Split output content to stdout and HTTP status code to stderr:

curl http://www.example.org -o >(cat >&1) -w "%{http_code}n" 1>&2

If only HTTP status code is desired to stderr, --silent can be used:

curl --silent http://www.example.org -o >(cat >&1) -w "%{http_code}n" 1>&2

The desired stream can then be picked by redirecting unwanted one to /dev/null:

$ (curl --silent http://www.example.org -o >(cat >&1) -w "%{http_code}" 1>&2) 1>/dev/null
200
$ (curl --silent http://www.example.org -o >(cat >&1) -w "%{http_code}" 1>&2) 2>/dev/null
<!doctype html>
...

Note that for the second redirection to behave as desired, we need to run the curl command in subshell.

answered Jun 4, 2019 at 8:08

Jaakko's user avatar

JaakkoJaakko

3102 silver badges12 bronze badges

2

The OP wants to know the status code. Often when downloading a file you also want to get a feel of it’s size so I’m using curl first to show status code and size of file and then shut off verbose and direct file to the place and name I want:

curl -R -s -S -w  "nhttp: %{http_code} %{size_download}n" -o /Users/myfiles/the_local_name.html http://archive.onweb.com/the_online_name.html

Then I wait for the finishing of curl

wait ${!}

before I run the next command. The above when used in a script of many commands like above gives a nice response like:

http: 200 42824

http: 200 34728

http: 200 35452

Please note that -o in curl needs to be followed by the full path of the file + name of file. This allows you thusly to save files in a sensible name structure when you d/l them with curl. Also note that -s and -S used together silence the output but does show errors. Note also that -R tries to set the file timestamp to that of the web file.

My answer is based on what @pvandenberk originally suggested, but in addition it actually saves the file somewhere, instead of merely directing to /dev/null.

Community's user avatar

answered Oct 7, 2017 at 7:32

sakumatto's user avatar

$ curl -kv https://www.example.org 2>&1 | grep -i 'HTTP/1.1 ' | awk '{print $3}'| sed -e 's/^[ t]*//'
  • 2>&1: error is stored in output for parsing
  • grep: filter the response code line from output
  • awk: filters out the response code from response code line
  • sed: removes any leading white spaces

answered Apr 14, 2021 at 4:44

Nitish Kumar's user avatar

There is another way by using Powershell command which is alias to curl.exe
Just type the following:

(Invoke-WebRequest -Uri https://your.website).StatusCode

answered Jul 14, 2022 at 10:30

Dmitrii L's user avatar

In Windows PowerShell:

curl https:\www.example.org -Method HEAD

It’s really just an alias for Invoke-WebRequest though.

answered Sep 14, 2022 at 18:24

Kebman's user avatar

KebmanKebman

5072 gold badges5 silver badges13 bronze badges

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

curl_getinfoВозвращает информацию об определённой операции

Описание

Список параметров

handle

Дескриптор cURL, полученный из curl_init().

option

Одна из перечисленных констант:


  • CURLINFO_EFFECTIVE_URL – Последний использованный URL

  • CURLINFO_HTTP_CODE – Последний код ответа.
    Начиная с cURL 7.10.8, это устаревший псевдоним
    CURLINFO_RESPONSE_CODE

  • CURLINFO_FILETIME – Удалённая (серверная) дата загруженного документа, если включена опция CURLOPT_FILETIME; если получено -1, значит это время неизвестно

  • CURLINFO_TOTAL_TIME – Общее время выполнения транзакции в секундах последней передачи

  • CURLINFO_NAMELOOKUP_TIME – Время разрешения имени сервера в секундах

  • CURLINFO_CONNECT_TIME – Время в секундах, затраченное на установку соединения

  • CURLINFO_PRETRANSFER_TIME – Время в секундах, прошедшее от начала операции до готовности к фактической передаче данных

  • CURLINFO_STARTTRANSFER_TIME – Время в секундах до передачи первого байта данных

  • CURLINFO_REDIRECT_COUNT – Число перенаправлений с включённой опцией CURLOPT_FOLLOWLOCATION

  • CURLINFO_REDIRECT_TIME – Общее время в секундах, затраченное на перенаправления до начала последней транзакции с включённой опцией CURLOPT_FOLLOWLOCATION

  • CURLINFO_REDIRECT_URL – При отключённой опции CURLOPT_FOLLOWLOCATION: URL перенаправления, найденный в прошлой итерации, который необходимо запрашивать вручную. Если опция CURLOPT_FOLLOWLOCATION включена: пустое значение. URL перенаправления в этом случае доступен в CURLINFO_EFFECTIVE_URL

  • CURLINFO_PRIMARY_IP – IP-адрес последнего соединения

  • CURLINFO_PRIMARY_PORT – Порт получателя последнего соединения

  • CURLINFO_LOCAL_IP – Локальный (исходящий) IP адрес последнего соединения

  • CURLINFO_LOCAL_PORT – Локальный (исходящий) порт последнего соединения

  • CURLINFO_SIZE_UPLOAD – Общее количество байт при закачке

  • CURLINFO_SIZE_DOWNLOAD – Общее количество байт при загрузке

  • CURLINFO_SPEED_DOWNLOAD – Средняя скорость загрузки

  • CURLINFO_SPEED_UPLOAD – Средняя скорость закачки

  • CURLINFO_HEADER_SIZE – Суммарный размер всех полученных заголовков

  • CURLINFO_HEADER_OUT – Посылаемая строка запроса. Для работы этого параметра, добавьте опцию CURLINFO_HEADER_OUT к дескриптору с помощью вызова curl_setopt()

  • CURLINFO_REQUEST_SIZE – Суммарный размер всех отправленных запросов, в настоящее время используется только для HTTP-запросов

  • CURLINFO_SSL_VERIFYRESULT – Результат проверки SSL-сертификата, запрошенной с помощью установки параметра CURLOPT_SSL_VERIFYPEER

  • CURLINFO_CONTENT_LENGTH_DOWNLOAD – размер скачанных данных, прочитанный из заголовка Content-Length:

  • CURLINFO_CONTENT_LENGTH_UPLOAD – Размер закачиваемых данных

  • CURLINFO_CONTENT_TYPE – Содержимое полученного заголовка Content-Type:. Если NULL, то сервер не послал правильный заголовок Content-Type:

  • CURLINFO_PRIVATE – Внутренние данные, связанные с данным cURL-обработчиком, ранее установленные с помощью опции CURLOPT_PRIVATE в функции curl_setopt()

  • CURLINFO_RESPONSE_CODE – Последний код возврата

  • CURLINFO_HTTP_CONNECTCODE – Код ответа операции CONNECT

  • CURLINFO_HTTPAUTH_AVAIL – Битовая маска, показывающая возможные методы аутентификации, доступные при предыдущем ответе

  • CURLINFO_PROXYAUTH_AVAIL – Битовая маска, показывающая возможные методы аутентификации на прокси, доступные при предыдущем ответе

  • CURLINFO_OS_ERRNO – Номер ошибки при попытке соединения. Код может различаться в зависимости от системы и ОС

  • CURLINFO_NUM_CONNECTS – Количество соединений, совершенных curl для обеспечения предыдущей передачи

  • CURLINFO_SSL_ENGINES – Поддержка OpenSSL

  • CURLINFO_COOKIELIST – Все известные куки

  • CURLINFO_FTP_ENTRY_PATH – Путь входа на FTP-сервер

  • CURLINFO_APPCONNECT_TIME – Время в секундах от начала и до установления SSL/SSH connect/handshake с удалённым хостом

  • CURLINFO_CERTINFO – связка ключей TLS

  • CURLINFO_CONDITION_UNMET – информация о неудовлетворённых временных условиях

  • CURLINFO_RTSP_CLIENT_CSEQ – Следующий RTSP клиентского CSeq

  • CURLINFO_RTSP_CSEQ_RECV – Недавно полученный CSeq

  • CURLINFO_RTSP_SERVER_CSEQ – Следующий RTSP серверного CSeq

  • CURLINFO_RTSP_SESSION_ID – ID сессии RTSP

  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T – Content-length загрузки. Это значение считывается из поля Content-Length:. -1 если размер не известен

  • CURLINFO_CONTENT_LENGTH_UPLOAD_T – Указанный размер загрузки. -1 если размер не известен

  • CURLINFO_HTTP_VERSION – Версия, использованная в последнем HTTP-соединении. Возвращаемое значение будет одной из определённых констант CURL_HTTP_VERSION_* или 0, если версия не может быть определена

  • CURLINFO_PROTOCOL – Протокол, использованный в последнем HTTP-соединении. Возвращаемое значение будет точно одним из значений CURLPROTO_*

  • CURLINFO_PROXY_SSL_VERIFYRESULT – Результат проверки сертификата, который был запрошен (с использованием параметра CURLOPT_PROXY_SSL_VERIFYPEER). Используется только для HTTPS-прокси

  • CURLINFO_SCHEME – Схема URL, используемая для самого последнего соединения

  • CURLINFO_SIZE_DOWNLOAD_T – Общее количество скачанных байтов. Номер предназначен только для последней передачи и будет сбрасываться для каждой новой передачи.

  • CURLINFO_SIZE_UPLOAD_T – Общее количество загруженных байтов

  • CURLINFO_SPEED_DOWNLOAD_T – Средняя скорость скачивания в байтах/секунду, измеренная для полного скачивания

  • CURLINFO_SPEED_UPLOAD_T – Средняя скорость загрузки в байтах/секунду, измеренная для полной загрузки

  • CURLINFO_APPCONNECT_TIME_T – Время в микросекундах, которое прошло с самого начала до тех пор, пока соединение/рукопожатие SSL/SSH не было завершено

  • CURLINFO_CONNECT_TIME_T – Общее время, затрачиваемое в микросекундах с начала до момента подключения к удалённому хосту (или прокси-серверу)

  • CURLINFO_FILETIME_T – Удалённое время извлечённого документа (как метка времени Unix), альтернатива CURLINFO_FILETIME, чтобы разрешить системам с 32-битными long-переменными извлекать даты вне диапазона 32-битных временных меток

  • CURLINFO_NAMELOOKUP_TIME_T -в Время в микросекундах от начала до разрешения имени

  • CURLINFO_PRETRANSFER_TIME_T – Время в микросекундах, затраченное с самого начала до начала передачи файла

  • CURLINFO_REDIRECT_TIME_T – Общее время в микросекундах, которое потребовалось для всех шагов перенаправления, включая поиск имени, подключение, предварительный перенос и передачу до запуска окончательной транзакции

  • CURLINFO_STARTTRANSFER_TIME_T – Время в микросекундах, которое прошло с начала до получения первого байта

  • CURLINFO_TOTAL_TIME_T – Общее время в микросекундах для предыдущей передачи, включая разрешение имён, TCP-соединение и т. д.

Возвращаемые значения

Если параметр 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() до выполнения запроса)

Учтите, что внутренние данные не добавляются в ассоциативный массив и должны получаться отдельно с помощью опции CURLINFO_PRIVATE.

Список изменений

Версия Описание
8.0.0 handle теперь ожидает экземпляр CurlHandle;
раньше, ожидался ресурс (resource).
8.0.0 option is nullable now;
previously, the default was 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.

Примеры

Пример #1 Пример использования curl_getinfo()


<?php
// Создаём дескриптор cURL
$ch = curl_init('http://www.example.com/');// Запускаем
curl_exec($ch);// Проверяем наличие ошибок
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
echo
'Прошло ', $info['total_time'], ' секунд во время запроса к ', $info['url'], "n";
}
// Закрываем дескриптор
curl_close($ch);
?>

Пример #2 Пример использования curl_getinfo() с параметром option


<?php
// Создаём дескриптор cURL
$ch = curl_init('http://www.example.com/');// Запускаем
curl_exec($ch);// Проверяем наличие ошибок
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);
?>

Примечания

Замечание:

Информация, собранная этой функцией, будет сохранена при дальнейшем
использовании дескриптора. Это означает, что если статистика не
будет перезаписана самой функцией, будет возвращаться информация
по предыдущему запросу.

ssttoo at hotmail dot com

19 years ago


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:
<?php
$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 handlerif (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: <br />";
        echo
$info['http_code'] . " " . $http_codes[$info['http_code']];
    }

}

?>


vince

12 years ago


CURLINFO_HTTP_CODE does not return a string, as the docs say, but rather an integer.

<?php
    $c
= curl_init('http://www.example.com/');
    if(
curl_getinfo($c, CURLINFO_HTTP_CODE) === '200') echo "CURLINFO_HTTP_CODE returns a string.";
    if(
curl_getinfo($c, CURLINFO_HTTP_CODE) === 200) echo "CURLINFO_HTTP_CODE returns an integer.";
   
curl_close($c);
?>

returns

"CURLINFO_HTTP_CODE returns an integer."


nikita dot bulatenko at gmail dot com

10 years ago


CURLINFO_SSL_VERIFYRESULT error codes:
0: ok the operation was successful.
2 : unable to get issuer certificate
3: unable to get certificate CRL
4: unable to decrypt certificate's signature
5: unable to decrypt CRL's signature
6: unable to decode issuer public key
7: certificate signature failure
8: CRL signature failure
9: certificate is not yet valid
10: certificate has expired
11: CRL is not yet valid
12:CRL has expired
13: format error in certificate's notBefore field
14: format error in certificate's notAfter field
15: format error in CRL's lastUpdate field
16: format error in CRL's nextUpdate field
17: out of memory
18: self signed certificate
19: self signed certificate in certificate chain
20: unable to get local issuer certificate
21:unable to verify the first certificate
22: certificate chain too long
23: certificate revoked
24: invalid CA certificate
25: path length constraint exceeded
26: unsupported certificate purpose
27: certificate not trusted
28: certificate rejected
29: subject issuer mismatch
30: authority and subject key identifier mismatch
31: authority and issuer serial number mismatch
32: key usage does not include certificate signing
50: application verification failure
details at http://www.openssl.org/docs/apps/verify.html#VERIFY_OPERATION

public-mail at alekciy dot ru

7 years ago


Note, header_size include "rnrn". So if you use CURLOPT_FOLLOWLOCATION>0, CURLOPT_HEADER=true, CURLOPT_RETURNTRANSFER=true right way splite header/body:

$response = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
$header_size = $curl_info['header_size'];
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);


qrworld.net

8 years ago


Here you have a function that I use to get the content of a URL using cURL. This uses curl_getinfo to know if it is a regular URL or maybe a redirection.

I hope it would be useful for you:

function getUrlContent($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode>=200 && $httpcode<300) ? $data : false;
}

The source comes from this website:

http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url.html


nemetral

14 years ago


Just a quick note: if you want to use curl_getinfo() with option CURLINFO_HEADER_OUT in order to debug your cURL request, you must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); first while specifying the options.

bg at enativ dot com

9 years ago


curl_getinfo($ch) will also return 'redirect_url' if there is one (even if CURLOPT_FOLLOWLOCATION set to false).
I don't know why it's not in the doc..

Mark Evers

15 years ago


There is a constant missing from that list.  CURLINFO_REDIRECT_COUNT will give you the number of redirects it went through if CURLOPT_FOLLOWLOCATION was set.

Anonymous

12 years ago


The main doc neglects to mention that when the CURLINFO_HEADER_OUT option is set the array returned by this function will included a new property, request_header, that is a string of the headers sent in the request.

Curly

8 years ago


If you call curl_reset() on a handle that has already been passed to curl_exec(), and then perform a curl_getinfo() on the same handle, you may expect that you get the same result as if you called curl_getinfo() immediately after curl_init(). This is not the case, however. cURL will return the data from the previous execution. If you want to completely reset you actually need to unset the cURL handle and recreate a new one.

torres dot krys at gmail dot com

7 years ago


If you use curl option CURLOPT_NOBODY = true to test if distant url is available, any sites can send you an http code 400 like Cdiscount Wsdl :

$ch = @curl_init($wsdl);

if($ch === false)
    return false;

        @curl_setopt($ch, CURLOPT_HEADER         ,true);    // we want headers
@curl_setopt($ch, CURLOPT_NOBODY         ,true);    // dont need body
@curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);    // catch output (do NOT print!)

@curl_exec($ch);

if(@curl_errno($ch)){   // should be 0
    @curl_close($ch);
    return false;
}

$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);

Modifying CURLOPT_NOBODY to false, http code sent is 200 otherwise http code is 400 !!!


luiheidsgoeroe at hotmail dot com

15 years ago


Keep in mind that for CURLOPT_RETURNTRANSFER it has to be set with curl_setopt() before execution:

This doesn't work:
<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>

This works:
<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>


These curl recipes show you how to debug curl requests to see what it’s sending and receiving. By default, curl only prints the response body. To make it print the full communication, including the request headers, SSL certificate information, response headers, and response body, use the -v command line argument. To make it print a hexdump of everything, use the --trace argument. To make it print both the response headers and the body, use the -i command line argument.

  1. Make Curl Verbose
  2. Detailed Trace
  3. Detailed Trace with Timestamps
  4. Include Response Headers in the Output
  5. Print Only the Response Headers
  6. Print Only the Request Headers
  7. Print Only the Response Code

Make Curl Verbose

curl -v https://catonmat.net

This recipe uses the -v argument to make curl print detailed information about the request and the response. Lines prefixed by > is the data sent to the server, lines prefixed by < is the data received from the server, and lines starting with * is misc information, such as connection information, SSL handshake information, and protocol information.

Detailed Trace

curl --trace - https://catonmat.net

In this recipe, we use the --trace - argument to enable full trace dump of all incoming and outgoing data. The trace dump prints hexdump of all bytes sent and received.

Detailed Trace with Timestamps

curl --trace - --trace-time https://catonmat.net

This recipe adds --trace-time argument to curl. This argument, combined with --trace - makes curl print a detailed trace log. You can also combine --trace-time with -v to add timestamps to curl’s verbose output.

curl -i https://catonmat.net

By default, curl prints the response body to the screen. This recipe uses the -i argument to make it also print response headers. When this flag is specified, curl will first print the response headers, then a blank line, then the response body.

curl -s -o /dev/null -D - https://catonmat.net

To print only the response headers (and discard the body), three arguments have to be used together. The -s argument makes curl silent and hides errors and progress bar, then -o /dev/null (if you’re on Windows, use -o NUL) makes curl ignore the response body, and -D - prints response headers to stdout (- is stdout).

curl -v -s -o /dev/null --stderr - https://catonmat.net | grep '^>'

There is no easy way to print just the request headers with curl. You have to shell out to an external helper program to do it and use a bunch of command line options to disable all other output. This recipe enables the verbose output via the -v argument, then makes curl silent via the -s argument, then makes curl ignore the output from the server via the -o /dev/null argument, then makes curl to redirect stderr to stdout via the --stderr - argument, and finally asks grep to print all lines that begin with > that contain request headers.

Print Only the Response Code

curl -w '%{response_code}' -s -o /dev/null https://catonmat.net

This recipe uses the -w argument that makes curl print extra information after the request has completed. The extra information we’re asking it to print is %{response_code} which is the response code of the request. To make curl only print the code and not the content or other information, we also use -s to silence curl and -o /dev/null that ignores the response output.

Created by Browserling

These curl recipes were written down by me and my team at Browserling. We use recipes like this every day to get things done and improve our product. Browserling itself is an online cross-browser testing service powered by alien technology. Check it out!

Secret message: If you love my curl recipe, then I love you, too! Use coupon code CURLLING to get a discount at my company.

Добавить комментарий