Вывести ошибку curl

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

curl_errorВозвращает строку с описанием последней ошибки текущего сеанса

Описание

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

handle

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

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

Возвращает сообщение об ошибке или '' (пустую строку),
если ошибки не произошло.

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

Версия Описание
8.0.0 handle теперь ожидает экземпляр CurlHandle;
раньше, ожидался ресурс (resource).

Примеры

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


<?php
// Создаём дескриптор curl к несуществующему адресу
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(

curl_exec($ch) === false)
{
echo
'Ошибка curl: ' . curl_error($ch);
}
else
{
echo
'Операция завершена без каких-либо ошибок';
}
// Закрываем дескриптор
curl_close($ch);
?>

patrick at ibuildings dot nl

10 years ago


If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string.

paul at paulmcgarry dot com

14 years ago


For a 404 response to actually trigger an error as the example seems to be trying to demonstrate the following option should be set:

curl_setopt($ch,CURLOPT_FAILONERROR,true);

As per http://curl.haxx.se/libcurl/c/libcurl-errors.html

CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400. (This error code was formerly known as CURLE_HTTP_NOT_FOUND.)


Anonymous

2 years ago


If you're using curl_multi and there's an error, curl_error() will remain empty until you've called curl_multi_info_read(). That function "pumps" the information inside the curl libraries to the point where curl_error() will return a useful string.

This should really be added to the documentation, because it's not at all obvious.


anrdaemon at freemail dot ru

4 years ago


curl_error is not a textual representation of curl_errno.
It's an actual error *message*.
If you want textual representation of error *code*, look for curl_strerror.

Вернуться к: cURL

curl_error

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

curl_errorВозвращает строку с описанием последней ошибки текущего сеанса

Описание

string curl_error
( resource $ch
)

Возвращает понятное сообщение об ошибке для последней операции cURL.

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

ch

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

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

Возвращает сообщение об ошибке или » (пустую строку),
если ошибки не произошло.

Примеры

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


<?php
// Создаем дескриптор curl к несуществующему адресу
$ch curl_init('http://404.php.net/');
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);

if(

curl_exec($ch) === false)
{
    echo 
'Ошибка curl: ' curl_error($ch);
}
else
{
    echo 
'Операция завершена без каких-либо ошибок';
}
// Закрываем дескриптор
curl_close($ch);
?>

Вернуться к: 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');

    ?>

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,4341 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,6671 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,4862 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.6k20 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 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 {

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

     }

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Выбивает ошибку на ноутбуке
  • Вывести ошибки php wordpress
  • Выбивает ошибку abs
  • Выберите то что является ошибкой при выполнении прыжка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии