Curl ошибка 500

Every HTTP request includes an HTTP response. An HTTP response is a set of metadata and a response body, where the body can occasionally be zero bytes and thus nonexistent. An HTTP response will however always have response headers.

Virtually all libcurl-using applications need to set at least one of those callbacks instructing libcurl what to do with received headers and data.

libcurl offers the curl_easy_getinfo() function that allows an application to query libcurl for information from the previously performed transfer.

Sometimes an application just want to know the size of the data. The size of a response as told by the server headers can be extracted with curl_easy_getinfo() like this:

curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &size);

If you can wait until after the transfer is already done, which also is a more reliable way since not all URLs will provide the size up front (like for example for servers that generate content on demand) you can instead ask for the amount of downloaded data in the most recent transfer.

curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD_T, &size);

Every HTTP response starts off with a single line that contains the HTTP response code. It is a three digit number that contains the server’s idea of the status for the request. The numbers are detailed in the HTTP standard specifications but they are divided into ranges that work like this:

Code

Meaning

1xx

Transient code, a new one follows

2xx

Things are OK

3xx

The content is somewhere else

4xx

Failed because of a client problem

5xx

Failed because of a server problem

You can extract the response code after a transfer like this

curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);

About HTTP response code «errors»

While the response code numbers can include numbers (in the 4xx and 5xx ranges) which the server uses to signal that there was an error processing the request, it is important to realize that this will not cause libcurl to return an error.

When libcurl is asked to perform an HTTP transfer it will return an error if that HTTP transfer fails. However, getting an HTTP 404 or the like back is not a problem for libcurl. It is not an HTTP transfer error. A user might be writing a client for testing a server’s HTTP responses.

If you insist on curl treating HTTP response codes from 400 and up as errors, libcurl offers the CURLOPT_FAILONERROR option that if set instructs curl to return CURLE_HTTP_RETURNED_ERROR in this case. It will then return error as soon as possible and not deliver the response body.

Львиная доля всех моих работ связана с работами по сео-оптимизации сайтов по требованиям сео-специалистов. Доработать, исправить, добавить, устранить… Очень часто нужно посмотреть ответы сервера по тому или иному url-адресу.

Проверку можно делать разными способами. Самым простым будет воспользоваться онлайн-тестами. Но это не наш вариант:)

В данном посте рассмотрим, какие возможности для данной задачи нам предоставляет curl.

Коды ответа сервера

Для начала рассмотрим самые распространенные коды ответа сервера:

1xx — информационные:

  • 100 — сервер принял первую часть запроса, можно подрожать передачу;
  • 101 — нужно изменить протокол работы на более подходящий;
  • 102 — на обработку запроса уйдет много времени, используется чтобы браузер не разрывал соединение раньше времени;

2хх — операция успешна:

  • 200 — запрос выполнен успешно, отправляется для большинства запрашиваемых страниц;
  • 201 — после выполнения запроса был создан ресурс;
  • 202 — запрос принят, но еще не обработан;
  • 203 — запрос выполнен успешно, но информация для ответа взята из прокси;
  • 204 — запрос обработан, но контента для отображения нет;
  • 205 — попросить пользователя ввести необходимые данные;
  • 206 — запрос обработан, но передана только часть контента;

3xx — перенаправления:

  • 300 — есть несколько страниц для этого запроса, например, на нескольких языках;
  • 301 — страница навсегда перемещена по новому адресу;
  • 302 — документ был временно перемещен;
  • 303 — документ необходимо загрузить по указанному адресу с помощью протокола GET;
  • 304 — документ не изменился с последнего запроса;
  • 305 — нужно использовать прокси;
  • 307 — ресурс временно перемещен на новый адрес.

4хх — ошибка в запросе:

  • 400 — неверный запрос;
  • 401 — необходимо аутентифицироваться;
  • 403 — запрос принят, но у вас нет доступа;
  • 404 — страница не найдена на сервере;
  • 405 — используемый метод нельзя применять на сервере;
  • 408 — время ожидания передачи запроса истекло;
  • 410 — ресурс полностью удален;
  • 411 — нужно указать длину запроса;
  • 413 — запрос слишком длинный;
  • 414 — URI запроса слишком длинная.

5хх — ошибка сервера:

  • 500 — внутренняя ошибка сервера;
  • 501 — нужная функция не поддерживается;
  • 502 — прокси не может соединиться со шлюзом;
  • 503 — сервер не может обрабатывать запросы по техническим причинам;
  • 504 — прокси не дождался ответа от сервера;
  • 505 — версия протокола HTTP не поддерживается.

Основные заголовки, отправляемые сервером

  • Server — имя и версия веб-сервера;
  • Date — дата осуществления запроса;
  • Content-Type — MIME тип передаваемых данных, например, text/html, тут же задается кодировка;
  • Connection — тип соединения, может быть closed — уже закрыто, или keep-alive — открыто для передачи данных;
  • Vary — указывает при каких заголовках веб-сервер будет возвращать разные старины для одного URI;
  • Set-Cookie — сохранить Cookie информацию для страницы;
  • Expires — можно хранить страницу или ресурс в кэше до определенной даты;
  • Cache-Control — настройка времени кэширования страницы браузером, а также разрешения на кэширования;
  • ETag — содержит контрольную сумму для страницы, применимо для проверки кэша;
  • Last-Modified — дата, когда страница последний раз была изменена;

Проверка кода ответа сервера с помощью curl

Чтобы увидеть только код ответа страницы достаточно выполнить такую команду:

curl -I https://pai-bx.com 2>/dev/null | head -n 1 | cut -d$' ' -f2

код ответа страницы

Как видим, сервер вернул 200 статус, что означает, что все ок. Страница доступна для чтения. Если проверить страницу, для которой должны быть настроены редиректы, получим 301-й статус:

Страница доступна для чтения.

Проверка http-заголовков с помощью curl

Чтобы вывести заголовки страницы необходимо запустить curl с опцией -I:

curl -I https://pai-bx.com

вывести заголовки страницы

Проверка IF-MODIFIED-SINCE

Чтобы увидеть работает ли данный заголовок, для начала выполняем обычный запрос заголовков сервера. Далее, повторяем отправку запроса, но уже с заголовком If-Modified-Since и датой:

IF-MODIFIED-SINCE

Видим, что второй запрос возвращает 304-й статус ответа, что означает, что с указанного времени страница не менялась и может быть взята из кеша браузера.

Таким образом, с помощью curl можно увидеть код ответа сервера и отдаваемые сервером заголовки.

What is cURL?

cURL is a widely used method of transferring data from and to (web)servers via URLs. It is installed on most, if not all webservers which makes it an ideal tool to use. Really Simple SSL uses cURL for a number of things. The plugin uses cURL to open your webpage to check if the site can load over SSL, to test if your certificate is valid, and to connect to really-simple-ssl.com to activate your Really Simple SSL Pro license. cURL works fine on the vast majority of webservers. However, it can fail in some environments, resulting in a cURL error. cURL errors cause some of the most common issues when using Really Simple SSL, for example, your license cannot activate or the plugin cannot retrieve the webpage to test for the mixed content fixer marker.

Important: cURL errors usually don’t break the front-end of your site, meaning that the site can still be visited by your users.

Why does a cURL error occur?

cURL errors are often caused by an outdated version of PHP or cURL. cURL errors are a good example of server-related errors. These are errors that aren’t caused by WordPress or Really Simple SSL, but by a server configuration. These errors usually won’t cause any issues on the front end of your site. If the site loads fine on https:// the error doesn’t impact your visitors.

How to fix a cURL error

Since cURL errors are server-related they can be fixed by your hosting provider. They have access to the server and can update PHP and/or cURL for you. This will solve a cURL error in most cases. If this doesn’t fix the cURL error, your hosting provider can tell you why cURL is not working correctly. It could be your hosting provider uses some form of security (for example a firewall) that is preventing the cURL request from completing.

cURL errors are given with a cURL error code, which provides more information about the reason why cURL has failed. This information is useful in troubleshooting the issue.

Most common cURL errors

cURL error 28: Connection timed out

cURL error 28 occurs when the cURL request isn’t completed in a certain amount of time. This happens when the cURL timeout value is set too low or when a firewall is blocking the cURL request. Another possibility is a security module, for example, the Apache mod_security module. To fix cURL error 28 you can contact your hosting provider.

cURL error 60: SSL certificate problem: unable to get local issuer certificate:

cURL error 60 occurs when the site uses an invalid SSL certificate. This error often occurs on localhost development environments since these usually don’t have a valid SSL certificate. If this error happens on your live site, contact your hosting provider to install a valid SSL certificate for you.

cURL error 35: SSL connect error

cURL error 35 is caused by a misconfiguration on the server. For example, an outdated certificate within cURL, or a mismatch in ciphers. Contact your hosting provider for a fix.

Below is the list of all cURL errors and the reasons behind these errors.

  • Ok
  • Unsupported Protocol
  • Failed Init
  • URL Malfomat
  • Not Built In
  • Couldn’t Resolve Proxy
  • Couldn’t resolve host
  • Couldn’t connect
  • Weird server reply
  • Remote access denied
  • FTP accept failed
  • FTP weird pass reply
  • FTP accept timeout
  • FTP weird pasv reply
  • FTP weird 227 format
  • FTP cant get host
  • HTTP2
  • FTP couldnt set type
  • Partial file
  • FTP couldnt retr file
  • Quote error
  • HTTP returned error
  • Write error
  • Upload failed
  • Read error
  • Out of memory
  • Operation timedout
  • FTP port failed
  • FTP couldnt use rest
  • Range error
  • HTTP post error
  • SSL connect error
  • Bad download resume
  • File couldnt read file
  • LDAP cannot bind
  • LDAP search failed
  • Function not found
  • Aborted by callback
  • Bad function argument
  • Interface failed
  • Too many redirects
  • Unknown option
  • Telnet option syntax
  • Got nothing
  • SSL engine notfound
  • SSL engine setfailed
  • Send error
  • Recv error
  • SSL certproblem
  • SSL cipher
  • PEER failed verification
  • Bad content encoding
  • LDAP invalid url
  • Filesize exceeded
  • Use ssl failed
  • Send fail rewind
  • SSL engine initfailed
  • Login denied
  • TFTP notfound
  • TFTP perm
  • Remote disk full
  • TFTP illegal
  • TFTP unknownid
  • Remote file exists
  • TFTP nosuchuser
  • Conv failed
  • Conv reqd
  • SSL cacert badfile
  • Remote file not found
  • SSH
  • SSL shutdown failed
  • Again
  • SSL crl badfile
  • SSL issuer error
  • FTP pret failed
  • RTSP cseq error
  • RTSP session error
  • FTP bad file list
  • Chunk failed
  • No connection available
  • SSL pinnedpubkeynotmatch
  • SSL invalidcertstatus
  • HTTP2 stream
  • Recursive api call
  • Auth error
  • HTTP3
  • Quic connect error
  • Obsolete*

Ok Ok

CURL error code 0 – CURLE_OK (0)

All fine. Proceed as usual.

Top ↑

Unsupported Protocol Unsupported Protocol

CURL error code 1 – CURLE_UNSUPPORTED_PROTOCOL (1)

The URL you passed to libcurl used a protocol that this libcurl does not support. The support might be a compile-time option that you didn’t use, it can be a misspelled protocol string or just a protocol libcurl has no code for.

Top ↑

Failed Init Failed Init

CURL error code 2 – CURLE_FAILED_INIT (2)

Very early initialization code failed. This is likely to be an internal error or problem, or a resource problem where something fundamental couldn’t get done at init time.

Top ↑

URL Malfomat URL Malfomat

CURL error code 3 – CURLE_URL_MALFORMAT (3)

The URL was not properly formatted.

Top ↑

Not Built In Not Built In

CURL error code 4 – CURLE_NOT_BUILT_IN (4)

A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. This means that a feature or option was not enabled or explicitly disabled when libcurl was built and in order to get it to function you have to get a rebuilt libcurl.

Top ↑

Couldn’t Resolve Proxy Couldn’t Resolve Proxy

CURL error code 5 – CURLE_COULDNT_RESOLVE_PROXY (5)

Couldn’t resolve proxy. The given proxy host could not be resolved.

Top ↑

Couldn’t resolve host Couldn’t resolve host

CURL error code 6 – CURLE_COULDNT_RESOLVE_HOST (6)

Couldn’t resolve host. The given remote host was not resolved.

Top ↑

Couldn’t connect Couldn’t connect

CURL error code 7 – CURLE_COULDNT_CONNECT (7)

Failed to connect() to host or proxy.

Top ↑

Weird server reply Weird server reply

CURL error code 8 – CURLE_WEIRD_SERVER_REPLY (8)

The server sent data libcurl couldn’t parse. This error code was known as as CURLE_FTP_WEIRD_SERVER_REPLY before 7.51.0.

Top ↑

Remote access denied Remote access denied

CURL error code 9 – CURLE_REMOTE_ACCESS_DENIED (9)

We were denied access to the resource given in the URL. For FTP, this occurs while trying to change to the remote directory.

Top ↑

FTP accept failed FTP accept failed

CURL error code 10 – CURLE_FTP_ACCEPT_FAILED (10)

While waiting for the server to connect back when an active FTP session is used, an error code was sent over the control connection or similar.

Top ↑

FTP weird pass reply FTP weird pass reply

CURL error code 11 – CURLE_FTP_WEIRD_PASS_REPLY (11)

After having sent the FTP password to the server, libcurl expects a proper reply. This error code indicates that an unexpected code was returned.

Top ↑

FTP accept timeout FTP accept timeout

CURL error code 12 – CURLE_FTP_ACCEPT_TIMEOUT (12)

During an active FTP session while waiting for the server to connect, the CURLOPT_ACCEPTTIMEOUT_MS (or the internal default) timeout expired.

Top ↑

FTP weird pasv reply FTP weird pasv reply

CURL error code 13 – CURLE_FTP_WEIRD_PASV_REPLY (13)

libcurl failed to get a sensible result back from the server as a response to either a PASV or a EPSV command. The server is flawed.

Top ↑

FTP weird 227 format FTP weird 227 format

CURL error code 14 – CURLE_FTP_WEIRD_227_FORMAT (14)

FTP servers return a 227-line as a response to a PASV command. If libcurl fails to parse that line, this return code is passed back.

Top ↑

FTP cant get host FTP cant get host

CURL error code 15 – CURLE_FTP_CANT_GET_HOST (15)

An internal failure to lookup the host used for the new connection.

Top ↑

HTTP2 HTTP2

CURL error code 16 – CURLE_HTTP2 (16)

A problem was detected in the HTTP2 framing layer. This is somewhat generic and can be one out of several problems, see the error buffer for details.

Top ↑

FTP couldnt set type FTP couldnt set type

CURL error code 17 – CURLE_FTP_COULDNT_SET_TYPE (17)

Received an error when trying to set the transfer mode to binary or ASCII.

Top ↑

Partial file Partial file

CURL error code 18 – CURLE_PARTIAL_FILE (18)

A file transfer was shorter or larger than expected. This happens when the server first reports an expected transfer size, and then delivers data that doesn’t match the previously given size.

Top ↑

FTP couldnt retr file FTP couldnt retr file

CURL error code 19 – CURLE_FTP_COULDNT_RETR_FILE (19)

This was either a weird reply to a ‘RETR’ command or a zero byte transfer complete.

Top ↑

Quote error Quote error

CURL error code 21 – CURLE_QUOTE_ERROR (21)

When sending custom “QUOTE” commands to the remote server, one of the commands returned an error code that was 400 or higher (for FTP) or otherwise indicated unsuccessful completion of the command.

Top ↑

HTTP returned error HTTP returned error

CURL error code 22 – 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.

Top ↑

Write error Write error

CURL error code 23 – CURLE_WRITE_ERROR (23)

An error occurred when writing received data to a local file, or an error was returned to libcurl from a write callback.

Top ↑

Upload failed Upload failed

CURL error code 25 – CURLE_UPLOAD_FAILED (25)

Failed starting the upload. For FTP, the server typically denied the STOR command. The error buffer usually contains the server’s explanation for this.

Top ↑

Read error Read error

CURL error code 26 – CURLE_READ_ERROR (26)

There was a problem reading a local file or an error returned by the read callback.

Top ↑

Out of memory Out of memory

CURL error code 27 – CURLE_OUT_OF_MEMORY (27)

A memory allocation request failed. This is serious badness and things are severely screwed up if this ever occurs.

Top ↑

Operation timedout Operation timedout

CURL error code 28 – CURLE_OPERATION_TIMEDOUT (28)

Operation timeout. The specified time-out period was reached according to the conditions.

Top ↑

FTP port failed FTP port failed

CURL error code 30 – CURLE_FTP_PORT_FAILED (30)

The FTP PORT command returned error. This mostly happens when you haven’t specified a good enough address for libcurl to use. See CURLOPT_FTPPORT.

Top ↑

FTP couldnt use rest FTP couldnt use rest

CURL error code 31 – CURLE_FTP_COULDNT_USE_REST (31)

The FTP REST command returned error. This should never happen if the server is sane.

Top ↑

Range error Range error

CURL error code 33 – CURLE_RANGE_ERROR (33)

The server does not support or accept range requests.

Top ↑

HTTP post error HTTP post error

CURL error code 34 – CURLE_HTTP_POST_ERROR (34)

This is an odd error that mainly occurs due to internal confusion.

Top ↑

SSL connect error SSL connect error

CURL error code 35 – CURLE_SSL_CONNECT_ERROR (35)

A problem occurred somewhere in the SSL/TLS handshake. You really want the error buffer and read the message there as it pinpoints the problem slightly more. Could be certificates (file formats, paths, permissions), passwords, and others.

Top ↑

Bad download resume Bad download resume

CURL error code 36 – CURLE_BAD_DOWNLOAD_RESUME (36)

The download could not be resumed because the specified offset was out of the file boundary.

Top ↑

File couldnt read file File couldnt read file

CURL error code 37 – CURLE_FILE_COULDNT_READ_FILE (37)

A file given with FILE:// couldn’t be opened. Most likely because the file path doesn’t identify an existing file. Did you check file permissions?

Top ↑

LDAP cannot bind LDAP cannot bind

CURL error code 38 – CURLE_LDAP_CANNOT_BIND (38)

LDAP cannot bind. LDAP bind operation failed.

Top ↑

LDAP search failed LDAP search failed

CURL error code 39 – CURLE_LDAP_SEARCH_FAILED (39)

LDAP search failed.

Top ↑

Function not found Function not found

CURL error code 41 – CURLE_FUNCTION_NOT_FOUND (41)

Function not found. A required zlib function was not found.

Top ↑

Aborted by callback Aborted by callback

CURL error code 42 – CURLE_ABORTED_BY_CALLBACK (42)

Aborted by callback. A callback returned “abort” to libcurl.

Top ↑

Bad function argument Bad function argument

CURL error code 43 – CURLE_BAD_FUNCTION_ARGUMENT (43)

A function was called with a bad parameter.

Top ↑

Interface failed Interface failed

CURL error code 45 – CURLE_INTERFACE_FAILED (45)

Interface error. A specified outgoing interface could not be used. Set which interface to use for outgoing connections’ source IP address with CURLOPT_INTERFACE.

Top ↑

Too many redirects Too many redirects

CURL error code 47 – CURLE_TOO_MANY_REDIRECTS (47)

Too many redirects. When following redirects, libcurl hit the maximum amount. Set your limit with CURLOPT_MAXREDIRS.

Top ↑

Unknown option Unknown option

CURL error code 48 – CURLE_UNKNOWN_OPTION (48)

An option passed to libcurl is not recognized/known. Refer to the appropriate documentation. This is most likely a problem in the program that uses libcurl. The error buffer might contain more specific information about which exact option it concerns.

Top ↑

Telnet option syntax Telnet option syntax

CURL error code 49 – CURLE_TELNET_OPTION_SYNTAX (49)

A telnet option string was Illegally formatted.

Top ↑

Got nothing Got nothing

CURL error code 52 – CURLE_GOT_NOTHING (52)

Nothing was returned from the server, and under the circumstances, getting nothing is considered an error.

Top ↑

SSL engine notfound SSL engine notfound

CURL error code 53 – CURLE_SSL_ENGINE_NOTFOUND (53)

The specified crypto engine wasn’t found.

Top ↑

SSL engine setfailed SSL engine setfailed

CURL error code 54 – CURLE_SSL_ENGINE_SETFAILED (54)

Failed setting the selected SSL crypto engine as default!

Top ↑

Send error Send error

CURL error code 55 – CURLE_SEND_ERROR (55)

Failed sending network data.

Top ↑

Recv error Recv error

CURL error code 56 – CURLE_RECV_ERROR (56)

Failure with receiving network data.

Top ↑

SSL certproblem SSL certproblem

CURL error code 58 – CURLE_SSL_CERTPROBLEM (58)

problem with the local client certificate.

Top ↑

SSL cipher SSL cipher

CURL error code 59 – CURLE_SSL_CIPHER (59)

Couldn’t use specified cipher.

Top ↑

PEER failed verification PEER failed verification

CURL error code 60 – CURLE_PEER_FAILED_VERIFICATION (60)

The remote server’s SSL certificate or SSH md5 fingerprint was deemed not OK. This error code has been unified with ## CURL error code – CURLE_SSL_CACERT since 7.62.0. Its previous value was 51.

Top ↑

Bad content encoding Bad content encoding

CURL error code 61 – CURLE_BAD_CONTENT_ENCODING (61)

Unrecognized transfer encoding.

Top ↑

LDAP invalid url LDAP invalid url

CURL error code 62 – CURLE_LDAP_INVALID_URL (62)

Invalid LDAP URL.

Top ↑

Filesize exceeded Filesize exceeded

CURL error code 63 – CURLE_FILESIZE_EXCEEDED (63)

Maximum file size exceeded.

Top ↑

Use ssl failed Use ssl failed

CURL error code 64 – CURLE_USE_SSL_FAILED (64)

Requested FTP SSL level failed.

Top ↑

Send fail rewind Send fail rewind

CURL error code 65 – CURLE_SEND_FAIL_REWIND (65)

When doing a send operation curl had to rewind the data to retransmit, but the rewinding operation failed.

Top ↑

SSL engine initfailed SSL engine initfailed

CURL error code 66 – CURLE_SSL_ENGINE_INITFAILED (66)

Initiating the SSL Engine failed.

Top ↑

Login denied Login denied

CURL error code 67 – CURLE_LOGIN_DENIED (67)

The remote server denied curl to login (Added in 7.13.1)

Top ↑

TFTP notfound TFTP notfound

CURL error code 68 – CURLE_TFTP_NOTFOUND (68)

File not found on TFTP server.

Top ↑

TFTP perm TFTP perm

CURL error code 69 – CURLE_TFTP_PERM (69)

Permission problem on TFTP server.

Top ↑

Remote disk full Remote disk full

CURL error code 70 – CURLE_REMOTE_DISK_FULL (70)

Out of disk space on the server.

Top ↑

TFTP illegal TFTP illegal

CURL error code 71 – CURLE_TFTP_ILLEGAL (71)

Illegal TFTP operation.

Top ↑

TFTP unknownid TFTP unknownid

CURL error code 72 – CURLE_TFTP_UNKNOWNID (72)

Unknown TFTP transfer ID.

Top ↑

Remote file exists Remote file exists

CURL error code 73 – CURLE_REMOTE_FILE_EXISTS (73)

File already exists and will not be overwritten.

Top ↑

TFTP nosuchuser TFTP nosuchuser

CURL error code 74 – CURLE_TFTP_NOSUCHUSER (74)

This error should never be returned by a properly functioning TFTP server.

Top ↑

Conv failed Conv failed

CURL error code 75 – CURLE_CONV_FAILED (75)

Character conversion failed.

Top ↑

Conv reqd Conv reqd

CURL error code 76 – CURLE_CONV_REQD (76)

Caller must register conversion callbacks.

Top ↑

SSL cacert badfile SSL cacert badfile

CURL error code 77 – CURLE_SSL_CACERT_BADFILE (77)

Problem with reading the SSL CA cert (path? access rights?)

Top ↑

Remote file not found Remote file not found

CURL error code 78 – CURLE_REMOTE_FILE_NOT_FOUND (78)

The resource referenced in the URL does not exist.

Top ↑

SSH SSH

CURL error code 79 – CURLE_SSH (79)

An unspecified error occurred during the SSH session.

Top ↑

SSL shutdown failed SSL shutdown failed

CURL error code 80 – CURLE_SSL_SHUTDOWN_FAILED (80)

Failed to shut down the SSL connection.

Top ↑

Again Again

CURL error code 81 – CURLE_AGAIN (81)

Socket is not ready for send/recv wait till it’s ready and try again. This return code is only returned from curl_easy_recv and curl_easy_send (Added in 7.18.2)

Top ↑

SSL crl badfile SSL crl badfile

CURL error code 82 – CURLE_SSL_CRL_BADFILE (82)

Failed to load CRL file (Added in 7.19.0)

Top ↑

SSL issuer error SSL issuer error

CURL error code 83 – CURLE_SSL_ISSUER_ERROR (83)

Issuer check failed (Added in 7.19.0)

Top ↑

FTP pret failed FTP pret failed

CURL error code 84 – CURLE_FTP_PRET_FAILED (84)

The FTP server does not understand the PRET command at all or does not support the given argument. Be careful when using CURLOPT_CUSTOMREQUEST, a custom LIST command will be sent with PRET CMD before PASV as well. (Added in 7.20.0)

Top ↑

RTSP cseq error RTSP cseq error

CURL error code 85 – CURLE_RTSP_CSEQ_ERROR (85)

Mismatch of RTSP CSeq numbers.

Top ↑

RTSP session error RTSP session error

CURL error code 86 – CURLE_RTSP_SESSION_ERROR (86)

Mismatch of RTSP Session Identifiers.

Top ↑

FTP bad file list FTP bad file list

CURL error code 87 – CURLE_FTP_BAD_FILE_LIST (87)

Unable to parse FTP file list (during FTP wildcard downloading).

Top ↑

Chunk failed Chunk failed

CURL error code 88 – CURLE_CHUNK_FAILED (88)

Chunk callback reported error.

Top ↑

No connection available No connection available

CURL error code 89 – CURLE_NO_CONNECTION_AVAILABLE (89)

(For internal use only, will never be returned by libcurl) No connection available, the session will be queued. (added in 7.30.0)

Top ↑

SSL pinnedpubkeynotmatch SSL pinnedpubkeynotmatch

CURL error code 90 – CURLE_SSL_PINNEDPUBKEYNOTMATCH (90)

Failed to match the pinned key specified with CURLOPT_PINNEDPUBLICKEY.

Top ↑

SSL invalidcertstatus SSL invalidcertstatus

CURL error code 91 – CURLE_SSL_INVALIDCERTSTATUS (91)

Status returned failure when asked with CURLOPT_SSL_VERIFYSTATUS.

Top ↑

HTTP2 stream HTTP2 stream

CURL error code 92 – CURLE_HTTP2_STREAM (92)

Stream error in the HTTP/2 framing layer.

Top ↑

Recursive api call Recursive api call

CURL error code 93 – CURLE_RECURSIVE_API_CALL (93)

An API function was called from inside a callback.

Top ↑

Auth error Auth error

CURL error code 94 – CURLE_AUTH_ERROR (94)

An authentication function returned an error.

Top ↑

HTTP3 HTTP3

CURL error code 95 – CURLE_HTTP3 (95)

A problem was detected in the HTTP/3 layer. This is somewhat generic and can be one out of several problems, see the error buffer for details.

Top ↑

Quic connect error Quic connect error

CURL error code 96 – CURLE_QUIC_CONNECT_ERROR (96)

QUIC connection error. This error may be caused by an SSL library error. QUIC is the protocol used for HTTP/3 transfers.

Top ↑

Obsolete* Obsolete*

CURL error code * – CURLE_OBSOLETE*

These error codes will never be returned. They were used in an old libcurl version and are currently unused.

Я использую функции 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 {

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

     }

Понравилась статья? Поделить с друзьями:
  • Cups waiting for job completed ошибка linux
  • Curl игнорировать ssl ошибку php
  • Curl 403 ошибка
  • Curl 28 ошибка samsung
  • Cyberpower ошибка ch9f