Php curl http error codes

Getting curl to output HTTP status code?

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?

As for me, I can see from the manual how to get the HTTP status code, but the option -w does not work. I have reported the bug to Apple.

The -i flag, as in curl -i https://www.example.com/ , is probably what you want, as per superuser.com/a/514798/190188

19 Answers 19

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

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

NB: curl -I does a HEAD HTTP request, which can be problematic for testing the HTTP status code for some web application servers and services

Don’t forget to redirect curl’s stderr: curl -I http://www.example.org 2>/dev/null | head -n 1 | cut -d$’ ‘ -f2 . Add -L to curl if you need the final status after redirects.

Forwarding stderr to /dev/null is not neccessary if you only want to suppress the progress bar — use -s switch for that.

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://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: % returns on first line of HTTP payload (available variables for the -w option on the curl documentation page)

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

-w «%» is the bit that prints the status code. You can add a newline or two in there to separate the code from the body (-w «\n\n%\n»)

Читайте также:  Создание временного файла php

I believe this downloads the entire file even though it all goes to /dev/null, so not ideal for checking the status code for huge files. httping -c 1 -s -G -m issues a GET and doesn’t download the whole file, although I realise this question is specifically about curl.

FYI: -s = Don’t show download progress, -o /dev/null = don’t display the body, -w «%» = Write http response code to stdout after exit.

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

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

the best answer as it makes curl output both headers and body, making it suitable for most of the tasks when used in a script

This is the best answer, and can be used in conjunction with -s (don’t show progress meter or error messages) and -S (do show error messages after all)

Sorry if one wants only the HTTP status code this answer is not doing that. pvandenberk’s answer that sends the output to /dev/null` does output only the three digit HTTP code by then requesting only the HTTP code in the format output.

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.

It even splits them in two different file outputs (http status details to stderr and response body to stdout)

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

Читайте также:  Css stylesheet black background

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 "%" into HTTP_STATUS # and sending the content to this command's STDOUT with -o >(cat >&3) HTTP_STATUS=$(curl -w "%" -o >(cat >&3) 'http://example.com') 

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

Источник

Получаем HTTP статус-коды сайта с помощью PHP и CURL

Используя нижеприведенный код вы сможете проверить, существует сайт или нет. Также можно проверить, есть ли на сайте редирект. Это может быть полезно для сайтов-каталогов, которые хотите проверить урлы, которые больше не являются активными или обновить свои ссылки. С помощью CURL мы получаем все статус коды для какого либо сайта, а затем ищем совпадения со списком HTTP статус-кодов.

$toCheckURL = «http://google.com» ; // Домен для проверки

curl_setopt( $ch , CURLOPT_URL, $toCheckURL );

curl_setopt( $ch , CURLOPT_HEADER, true);

curl_setopt( $ch , CURLOPT_NOBODY, true);

curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true);

curl_setopt( $ch , CURLOPT_FOLLOWLOCATION, true);

curl_setopt( $ch , CURLOPT_MAXREDIRS, 10); // разрешаем только 10 редиректов за раз во избежание бесконечного цикла

$http_code = curl_getinfo( $ch , CURLINFO_HTTP_CODE); // Получаем HTTP-код

$new_url = curl_getinfo( $ch , CURLINFO_EFFECTIVE_URL);

// Массив возможных HTTP статус кодовв

$codes = array (0=> ‘Domain Not Found’ ,

203=> ‘Non-Authoritative Information’ ,

407=> ‘Proxy Authentication Required’ ,

413=> ‘Request Entity Too Large’ ,

415=> ‘Unsupported Media Type’ ,

416=> ‘Requested Range Not Satisfiable’ ,

500=> ‘Internal Server Error’ ,

505=> ‘HTTP Version Not Supported’ );

// Ищем совпадения с нашим списком

if (isset( $codes [ $http_code ]))

echo ‘Сайт вернул ответ: ‘ . $http_code . ‘ — ‘ . $codes [ $http_code ]. ‘
‘ ;

preg_match_all( «/HTTP/1.[1|0]s(d)/» , $data , $matches );

// Идем дальше по списку, чтобы посмотреть, какие мы еще статус коды получили

Читайте также:  How to get day in javascript

// Проверяем если урл поменялся или нет

Источник

antriver / PHP array of cURL error codes and strings

Here’s an array of cURL error codes and their respective constant names as strings. If you’re looking for an array of descriptions of cURL error codes then look here: http://drewsbox.com/php-snippets/php-array-of-curl-errors

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

$curl_error_codes = array (
0 => ‘CURLE_OK’,
1 => ‘CURLE_UNSUPPORTED_PROTOCOL’,
2 => ‘CURLE_FAILED_INIT’,
3 => ‘CURLE_URL_MALFORMAT’,
4 => ‘CURLE_NOT_BUILT_IN’,
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’,
10 => ‘CURLE_FTP_ACCEPT_FAILED’,
11 => ‘CURLE_FTP_WEIRD_PASS_REPLY’,
12 => ‘CURLE_FTP_ACCEPT_TIMEOUT’,
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_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’,
85 => ‘CURLE_RTSP_CSEQ_ERROR’,
86 => ‘CURLE_RTSP_SESSION_ERROR’,
87 => ‘CURLE_FTP_BAD_FILE_LIST’,
88 => ‘CURLE_CHUNK_FAILED’,
89 => ‘CURLE_NO_CONNECTION_AVAILABLE’
);
?>

Источник

Оцените статью