Утилита командной строки curl

PROTOCOLS

curl supports numerous protocols, or put in URL terms: schemes. Your particular build may not support them all.

DICT

Lets you lookup words using online dictionaries.

FILE

Read or write local files. curl does not support accessing file:// URL remotely, but when running on Microsoft Windows using the native UNC approach will work.

FTP(S)

curl supports the File Transfer Protocol with a lot of tweaks and levers. With or without using TLS.

GOPHER(S)

Retrieve files.

HTTP(S)

curl supports HTTP with numerous options and variations. It can speak HTTP version 0.9, 1.0, 1.1, 2 and 3 depending on build options and the correct command line options.

IMAP(S)

LDAP(S)

curl can do directory lookups for you, with or without TLS.

MQTT

curl supports MQTT version 3. Downloading over MQTT equals «subscribe» to a topic while uploading/posting equals «publish» on a topic. MQTT over TLS is not supported (yet).

POP3(S)

Downloading from a pop3 server means getting a mail. With or without using TLS.

RTMP(S)

The Realtime Messaging Protocol is primarily used to server streaming media and curl can download it.

RTSP

curl supports RTSP 1.0 downloads.

SCP

curl supports SSH version 2 scp transfers.

SFTP

curl supports SFTP (draft 5) done over SSH version 2.

SMB(S)

curl supports SMB version 1 for upload and download.

SMTP(S)

TELNET

Telling curl to fetch a telnet URL starts an interactive session where it sends what it reads on stdin and outputs what the server sends it.

TFTP

curl can do TFTP downloads and uploads.

Cookie options

The simplest way to send a few cookies to the server when getting a page with curl is to add them on the command line like:

Cookies are sent as common HTTP headers. This is practical as it allows curl to record cookies simply by recording headers. Record cookies with curl by using the () option like:

(Take note that the option described below is a better way to store cookies.)

Curl has a full blown cookie parsing engine built-in that comes in use if you want to reconnect to a server and use cookies that were stored from a previous connection (or hand-crafted manually to fool the server into believing you had a previous connection). To use previously stored cookies, you run curl like:

Curl’s «cookie engine» gets enabled when you use the option. If you only want curl to understand received cookies, use with a file that doesn’t exist. Example, if you want to let curl understand cookies from a page and follow a location (and thus possibly send back cookies it received), you can invoke it like:

Curl has the ability to read and write cookie files that use the same file format that Netscape and Mozilla once used. It is a convenient way to share cookies between scripts or invokes. The () switch automatically detects if a given file is such a cookie file and parses it, and by using the () option you’ll make curl write a new cookie file at the end of an operation:

Показать заголовок запроса и ответа

Если хотите удостовериться, что получаете ожидаемый заголовок запроса и ответа, используйте следующую команду:

# curl -v yoururl.com

например:

# curl -v 74.125.68.100   
* About to connect() to 74.125.68.100 port 80 (#0)   
*   Trying 74.125.68.100...   
* Connected to 74.125.68.100 (74.125.68.100) port 80 (#0)   
> GET / HTTP/1.1   
> User-Agent: curl/7.29.0   
>Host: 74.125.68.100   
>Accept: */*   
>< HTTP/1.1 200 OK   
<Date: Sun, 18 Jan 2015 06:02:58 GMT   
<Expires: -1   
< Cache-Control: private, max-age=0   
< Content-Type: text/html; charset=utf-8   
< Set-Cookie: NID=67=EZH_o3sPvCSnxzVatz21OHv_; 
expires=Mon, 20-Jul-2015 06:02:58 GMT; 
path=/; 
domain=.; HttpOnly
< P3P: CP="This is not a P3P policy! 
See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for moreinfo."   
< Server: gws
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN   
<Alternate-Protocol: 80:quic,p=0.02   
<Accept-Ranges: none
<Vary: Accept-Encoding
<Transfer-Encoding: chunked

User Agent

An HTTP request has the option to include information about the browser that generated the request. Curl allows it to be specified on the command line. It is especially useful to fool or trick stupid servers or CGI scripts that only accept certain browsers.

Example:

Other common strings:

  • — Netscape Version 3 for Windows 95
  • — Netscape Version 3 for Windows 95
  • — Netscape Version 2 for OS/2
  • — Netscape for AIX
  • — Netscape for Linux

Note that Internet Explorer tries hard to be compatible in every way:

Mozilla/4.0 (compatible; MSIE 4.01; Windows 95) — MSIE for W95

Mozilla is not the only possible User-Agent name:

  • — KDE File Manager desktop client
  • — Lynx command line browser

Some login tricks

While not strictly just HTTP related, it still causes a lot of people problems so here’s the executive run-down of how the vast majority of all login forms work and how to login to them using curl.

It can also be noted that to do this properly in an automated fashion, you will most certainly need to script things and do multiple curl invokes etc.

First, servers mostly use cookies to track the logged-in status of the client, so you will need to capture the cookies you receive in the responses. Then, many sites also set a special cookie on the login page (to make sure you got there through their login page) so you should make a habit of first getting the login-form page to capture the cookies set there.

Some web-based login systems feature various amounts of javascript, and sometimes they use such code to set or modify cookie contents. Possibly they do that to prevent programmed logins, like this manual describes how to… Anyway, if reading the code isn’t enough to let you repeat the behavior manually, capturing the HTTP requests done by your browsers and analyzing the sent cookies is usually a working method to work out how to shortcut the javascript need.

In the actual tag for the login, lots of sites fill-in random/session or otherwise secretly generated hidden tags and you may need to first capture the HTML code for the login form and extract all the hidden fields to be able to do a proper login POST. Remember that the contents need to be URL encoded when sent in a normal POST.

IPv6

curl will connect to a server with IPv6 when a host lookup returns an IPv6 address and fall back to IPv4 if the connection fails. The and options can specify which address to use when both are available. IPv6 addresses can also be specified directly in URLs using the syntax:

When this style is used, the option must be given to stop curl from interpreting the square brackets as special globbing characters. Link local and site local addresses including a scope identifier, such as , may also be used, but the scope portion must be numeric or match an existing network interface on Linux and the percent character must be URL escaped. The previous example in an SFTP URL might look like:

IPv6 addresses provided other than in URLs (e.g. to the , or options) should not be URL encoded.

Submitting JSON data with cURL

In the previous section, we have seen how can submit POST requests using cURL. You can also submit JSON data using the  option. However, most servers expect to receive a POST request with key-value pairs, similar to the ones we have discussed previously. So, you need to add an additional header called ‘Content-Type: application/json’ so that the server understands it’s dealing with JSON data and handles it appropriately. Also, you don’t need to URL-encode data when submitting JSON.

So if you had the following JSON data and want to make a POST request to https://httpbin.org/post:

{
  "email": "",
  "name": 
}

Then, you can submit the data with:

curl --data '{"email":"", "name": }' -H 'Content-Type: application/json' https://httpbin.org/post

In this case, you can see the data appear under the  value in the httpbin.org output:

You can also save the JSON file, and submit it in the same way as we did previously:

curl --data @data.json https://httpbin.org/post

Install cURL

Linux

Most Linux distributions have cURL installed by default. To check whether it is installed on your system or not, type  in your terminal window and press enter. If it isn’t installed, it will show a “command not found” error. Use the commands below to install it on your system.

For Ubuntu/Debian based systems use:

sudo apt update
sudo apt install curl

For CentOS/RHEL systems, use:

sudo yum install curl

On the other hand, for Fedora systems, you can use the command:

sudo dnf install curl

MacOS

MacOS comes with cURL preinstalled, and it receives updates whenever Apple releases updates for the OS. However, in case you want to install the most recent version of cURL, you can install the Homebrew package. Once you install Homebrew, you can install it with:

brew install curl

Windows

For Windows 10 version 1803 and above, cURL now ships by default in the Command Prompt, so you can use it directly from there. For older versions of Windows, the cURL project has Windows binaries. Once you download the ZIP file and extract it, you will find a folder named .  Move this folder into a directory of your choice. In this article, we will assume our folder is named , and we have moved it under .

Next, you should add cURL’s  directory to the Windows  environment variable, so that Windows can find it when you type  in the command prompt. For this to work, you need to follow these steps:

  • Open the “Advanced System Properties” dialog by running  from the Windows Run dialog (Windows key + R).
  • Click on the “Environment Variables” button.
  • Double-click on “Path” from the “System variables” section, and add the path . For Windows 10, you can do this with the “New” button on the right. On older versions of Windows, you can type in  (notice the semicolon at the beginning) at the end of the “Value” text box.

Once you complete the above steps, you can type  to check if this is working. If everything went well, you should see the following output:

C:\Users\Administrator>curl
curl: try 'curl --help' or 'curl --manual' for more information

Some debug tricks

Many times when you run curl on a site, you’ll notice that the site doesn’t seem to respond the same way to your curl requests as it does to your browser’s.

Then you need to start making your curl requests more similar to your browser’s requests:

  • Use the option to store fully detailed logs of the requests for easier analyzing and better understanding

  • Make sure you check for and use cookies when needed (both reading with and writing with )

  • Set user-agent (with ) to one like a recent popular browser does

  • Set referer (with ) like it is set by the browser

  • If you use POST, make sure you send all the fields and in the same order as the browser does it.

curl_getinfo

curl_getinfo — получает информацию, касающуюся специфической передачи/transfer.

Описание

string curl_getinfo (resource ch, int opt)

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

  • CURLINFO_HTTP_CODE — Последний полученный код
    HTTP

  • CURLINFO_FILETIME — Дата модификации
    загруженного документа, если она неизвестна, возвращается -1.

  • CURLINFO_TOTAL_TIME — Полное время выполнения
    операции в секундах.

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

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

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

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

  • CURLINFO_REDIRECT_TIME — Общее время,
    затраченное на перенапрвления, в секундах

  • CURLINFO_SIZE_UPLOAD — Количество байт при
    закачке

  • CURLINFO_SIZE_DOWNLOAD — Количество байт при
    загрузке

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

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

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

  • 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 в случае, когда этот
    заголовок не был получен

При вызове без необязательного аргумента opt
возвращается ассоциативный массив со следующими индексами, которые
соответствуют значениям аргумента opt:

  • «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»

Пример использования curl_getinfo:
$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));
Пример использования curl_getinfo:
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
    die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL,            "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER,         1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT,        30);

// execute
$ret = curl_exec($ch);

if (empty($ret)) {
    // some kind of an error happened
    die(curl_error($ch));
    curl_close($ch); // close cURL handler
} else {
    $info = curl_getinfo($ch);
    curl_close($ch); // close cURL handler

    if (empty($info)) {
            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_codes];
    }

}

Как работать с cURL гораздо проще

Вы можете спросить: почему у cURL такие кривые и страшные методы? У вас может возникнуть желание взять и создать обертку для работы с cURL, чтобы вы могли не писать каждый раз большие куски некрасивого кода, а писать все проще, например так:

$curl = new Curl();
$curl->get('https://www.example.com/search', );

Или так:

$curl = new Curl();
$curl->post('https://www.example.com/login/', );

К счастью, такая обертка уже написана и найти ее можно здесь: https://github.com/php-curl-class/php-curl-class

Просто установите ее при помощи:

и не работайте с кривыми кусками кода, которые таковы вероятно потому, что cURL изначально консольное приложение.

Persistent Connections

Specifying multiple files on a single command line will make curl transfer all of them, one after the other in the specified order.

libcurl will attempt to use persistent connections for the transfers so that the second transfer to the same host can use the same connection that was already initiated and was left open in the previous transfer. This greatly decreases connection time for all but the first transfer and it makes a far better use of the network.

Note that curl cannot use persistent connections for transfers that are used in subsequence curl invokes. Try to stuff as many URLs as possible on the same command line if they are using the same host, as that’ll make the transfers faster. If you use an HTTP proxy for file transfers, practically all transfers will be persistent.

Viewing request headers and connection details

In the previous section, we have seen how you can view HTTP response headers using cURL. However, sometimes you may want to view more details about a request, such as the request headers sent and the connection process. cURL offers the  flag (called “verbose mode”) for this purpose, and it can be used as follows:

curl -v https://www.booleanworld.com/

The output contains request data (marked with ), response headers (marked with ) and other details about the request, such as the IP used and the SSL handshake process (marked with ). The response body is also available below this information. (However, this is not visible in the screenshot below).

Most often, we aren’t interested in the response body. You can simply hide it by “saving” the output to the null device, which is  on Linux and MacOS and  on Windows:

curl -vo /dev/null https://www.booleanworld.com/ # Linux/MacOS
curl -vo NUL https://www.booleanworld.com/ # Windows

3: Поддержка перенаправлений

Пока что все примеры использовали полностью определенные URL-адреса, которые включают протокол https://. Если бы вы попытались получить файл robots.txt и указали бы только домен, вы не увидели бы никаких результатов, потому что сайт может перенаправлять запросы с http:// на https://.

Вы можете проверить это с помощью флага -I, который отображает заголовки запроса, а не содержимое файла:

Выходные данные показывают, что URL-адрес был перенаправлен. Первая строка вывода сообщает, что он был перемещен, а строка Location сообщает, куда именно:

Вы можете использовать curl и отправить другой запрос вручную. Также вы можете использовать аргумент –location (или –L), который позволит утилите curl отправить запрос в новое место, если она встречает перенаправление. Попробуйте сделать это:

На этот раз вы увидите ожидаемый результат, поскольку curl поддерживает перенаправление:

Вы можете комбинировать аргумент -L с некоторыми из вышеупомянутых аргументов, чтобы загрузить файл в вашу локальную систему:

Важно! Многие онлайн-ресурсы предлагают использовать curl для загрузки скриптов и их выполнения. Однако прежде чем делать исполняемыми и запускать какие-либо загруженные скрипты, вы должны проверить их содержимое

Используйте команду less, чтобы проверить код и убедиться, что он не причинит вреда вашей системе.

Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds

In order to compile libcurl and curl using BSD-style lwIP TCP/IP stack it is
necessary to make definition of preprocessor symbol visible to
libcurl and curl compilation processes. To set this definition you have the
following alternatives:

  • Modify and
  • Modify
  • Modify the «Preprocessor Definitions» in the libcurl project

Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Settings -> C/C++ -> General» in VC6 and «Project ->
Properties -> Configuration Properties -> C/C++ -> Preprocessor» in later
versions.

Once that libcurl has been built with BSD-style lwIP TCP/IP stack support, in
order to use it with your program it is mandatory that your program includes
lwIP header file (or another lwIP header that includes this)
before including any libcurl header. Your program does not need the
preprocessor definition which is for libcurl internals only.

This BSD-style lwIP TCP/IP stack support must be considered experimental given
that it has been verified that lwIP 1.4.0 still needs some polish, and libcurl
might yet need some additional adjustment, caveat emptor.

PROGRESS METER

curl normally displays a progress meter during operations, indicating the amount of transferred data, transfer speeds and estimated time left, etc. The progress meter displays number of bytes and the speeds are in bytes per second. The suffixes (k, M, G, T, P) are 1024 based. For example 1k is 1024 bytes. 1M is 1048576 bytes.

curl displays this data to the terminal by default, so if you invoke curl to do an operation and it is about to write data to the terminal, it disables the progress meter as otherwise it would mess up the output mixing progress meter and response data.

If you want a progress meter for HTTP POST or PUT requests, you need to redirect the response output to a file, using shell redirect (>), or similar.

This does not apply to FTP upload as that operation does not spit out any response data to the terminal.

If you prefer a progress «bar» instead of the regular meter, -#, —progress-bar is your friend. You can also disable the progress meter completely with the option.

Time Conditions

HTTP allows a client to specify a time condition for the document it requests. It is or . curl allows you to specify them with the / flag.

For example, you can easily make a download that only gets performed if the remote file is newer than a local copy. It would be made like:

Or you can download a file only if the local file is newer than the remote one. Do this by prepending the date string with a , as in:

You can specify a «free text» date as condition. Tell curl to only download the file if it was updated since January 12, 2012:

Curl will then accept a wide range of date formats. You always make the date check the other way around by prepending it with a dash ().

Progress Meter

The progress meter exists to show a user that something actually is happening. The different fields in the output have the following meaning:

From left-to-right:

  • % — percentage completed of the whole transfer
  • Total — total size of the whole expected transfer
  • % — percentage completed of the download
  • Received — currently downloaded amount of bytes
  • % — percentage completed of the upload
  • Xferd — currently uploaded amount of bytes
  • Average Speed Dload — the average transfer speed of the download
  • Average Speed Upload — the average transfer speed of the upload
  • Time Total — expected time to complete the operation
  • Time Current — time passed since the invoke
  • Time Left — expected time left to completion
  • Curr.Speed — the average transfer speed the last 5 seconds (the first 5 seconds of a transfer is based on less time of course.)

The option will display a totally different progress bar that doesn’t need much explanation!

Множественный cURL

Одной из самых сильных сторон cURL является возможность создания «множественных» cURL обработчиков. Это позволяет вам открывать соединение к множеству URL одновременно и асинхронно.

В классическом варианте cURL запроса выполнение скрипта приостанавливается, и происходит ожидание завершения операции URL запроса, после чего работа скрипта может продолжиться. Если вы намереваетесь взаимодействовать с целым множеством URL, это приведёт к довольно-таки значительным затратам времени, поскольку в классическом варианте вы можете работать только с одним URL за один раз. Однако, мы можем исправить данную ситуацию, воспользовавшись специальными обработчиками.

Давайте рассмотрим пример кода, который я взял с php.net:

// создаём несколько cURL ресурсов
$ch1 = curl_init();
$ch2 = curl_init();

// указываем URL и другие параметры
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//создаём множественный cURL обработчик
$mh = curl_multi_init();

//добавляем несколько обработчиков
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//выполнение
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//закрытие
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

Идея состоит в том, что вы можете использовать множественные cURL обработчики. Используя простой цикл, вы можете отследить, какие запросы ещё не выполнились.

В этом примере есть два основных цикла. Первый цикл do-while вызывает функцию curl_multi_exec(). Эта функция не блокируемая. Она выполняется с той скоростью, с которой может, и возвращает состояние запроса. Пока возвращенное значение является константой ‘CURLM_CALL_MULTI_PERFORM’, это означает, что работа ещё не завершена (например, в данный момент происходит отправка http заголовков в URL); Именно поэтому мы продолжаем проверять это возвращаемое значение, пока не получим другой результат.

В следующем цикле мы проверяем условие, пока переменная $active = ‘true’. Она является вторым параметром для функции curl_multi_exec(). Значение данной переменной будет равно ‘true’, до тех пор, пока какое-то из существующих изменений является активным. Далее мы вызываем функцию curl_multi_select(). Её выполнение ‘блокируется’, пока существует хоть одно активное соединение, до тех пор, пока не будет получен ответ. Когда это произойдёт, мы возвращаемся в основной цикл, чтобы продолжить выполнение запросов.

А теперь давайте применим полученные знания на примере, который будет реально полезным для большого количества людей.

Building from git

If you get your code off a git repository instead of a release tarball, see
the file in the root directory for specific instructions on how to
proceed.

Unix

A normal Unix installation is made in three or four steps (after you’ve
unpacked the source archive):

(Adjust the configure line accordingly to use the TLS library you want.)

You probably need to be root when doing the last command.

Get a full listing of all available configure options by invoking it like:

If you want to install curl in a different file hierarchy than ,
specify that when running configure:

If you have write permission in that directory, you can do ‘make install’
without being root. An example of this would be to make a local install in
your own home directory:

The configure script always tries to find a working SSL library unless
explicitly told not to. If you have OpenSSL installed in the default search
path for your compiler/linker, you don’t need to do anything special. If you
have OpenSSL installed in , you can run configure like:

If you have OpenSSL installed somewhere else (for example, ) and
you have pkg-config installed, set the pkg-config path first, like this:

Without pkg-config installed, use this:

If you insist on forcing a build without SSL support, even though you may
have OpenSSL installed in your system, you can run configure like this:

If you have OpenSSL installed, but with the libraries in one place and the
header files somewhere else, you have to set the and
environment variables prior to running configure. Something like this should
work:

If you have shared SSL libs installed in a directory where your run-time
linker doesn’t find them (which usually causes configure failures), you can
provide this option to gcc to set a hard-coded path to the run-time linker:

Пример CURL – вызываем удаленный скрипт и получаем результат

Сейчас давайте попробуем вызвать скрипт и получить результат, для того чтобы потом его обработать, для примера давайте использовать метод POST. Названия файлов оставим такими же.

Код test_curl.php

<?PHP
        //Инициализирует сеанс
        $connection = curl_init();
        //Устанавливаем адрес для подключения
        curl_setopt($connection, CURLOPT_URL, "http://localhost/test/test.php");
        //Указываем, что мы будем вызывать методом POST
        curl_setopt($connection, CURLOPT_POST, 1);
        //Передаем параметры методом POST
        curl_setopt($connection, CURLOPT_POSTFIELDS, "id=1");
        //Говорим, что нам необходим результат
        curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
        //Выполняем запрос с сохранением результата в переменную
        $rezult=curl_exec($connection);
        //Завершает сеанс
        curl_close($connection);
        //Выводим на экран
        echo $rezult * 100;
?>

Код test.php

<?PHP
        //Принимаем методом POST
        if (isset($_POST)){
                $id = (int)$_POST;
                //Получаем значение на основе id
                switch($id){
                                case 1:
                                        $itog = 1.11;
                                        break;
                                case 2:
                                        $itog = 2.22;
                                        break;
                                case 3:
                                        $itog = 3.33;
                                        break;                                  
                }
                echo $itog;
        }
?>

И если мы запустим test_curl.php то на экран у нас выведется 111, т.е. 1.11 полученное в результате обращения к удаленному скрипту, умноженное на 100.

А теперь давайте поговорим о функциях и константах к ним.

Following redirects with cURL

By default, when cURL receives a redirect after making a request, it doesn’t automatically make a request to the new URL. As an example of this, consider the URL . When you make a request using to this URL, the server sends a HTTP 3XX redirect to . However,  the response body is otherwise empty. So, if you try this out, you will get an empty output:

If you want cURL to follow these redirects, you should use the option. If you repeat make a request for  with the  flag, like so:

curl -L http://www.facebook.com/

Now, you will be able to see the HTML content of the page, similar to the screenshot below. In the next section, we will see how we can verify that there is a HTTP 3XX redirect.

Please bear in mind that cURL can only follow redirects if the server replied with a “HTTP redirect”, which means that the server used a 3XX status code, and it used the “Location” header to indicate the new URL. cURL cannot process Javascript or HTML-based redirection methods, or the ““.

If there is a chain of redirects, the option will only follow the redirects up to 500 times. You can control the number of maximum redirects that it will follow with the flag.

curl -L --max-redirs 700 example.com

If you set this flag to , it will follow the redirects endlessly.

curl -L --max-redirs -1 example.com

Changing the request method

Previously, we have seen how you can send POST requests with cURL. Sometimes, you may need to send a POST request with no data at all. In that case, you can simply change the request method to POST with the  option, like so:

curl -X POST https://httpbin.org/post

You can also change the request method to anything else, such as PUT, DELETE or PATCH. One notable exception is the HEAD method, which cannot be set with the  option. The HEAD method is used to check if a document is present on the server, but without downloading the document. To use the HEAD method, use the  option:

curl -I https://www.booleanworld.com/

When you make a HEAD request, cURL displays all the request headers by default. Servers do not send any content when they receive a HEAD request, so there is nothing after the headers:

85 Operating Systems

AIX, AmigaOS, Android, Aros, BeOS, Blackberry 10, Blackberry Tablet OS, Cell
OS, ChromeOS, Cisco IOS, Cygwin, Dragonfly BSD, eCOS, FreeBSD, FreeDOS,
FreeRTOS, Fuchsia, Garmin OS, Genode, Haiku, HardenedBSD, HP-UX, Hurd,
Illumos, Integrity, iOS, ipadOS, IRIX, LineageOS, Linux, Lua RTOS, Mac OS 9,
macOS, Mbed, Micrium, MINIX, MorphOS, MPE/iX, MS-DOS, NCR MP-RAS, NetBSD,
Netware, Nintendo Switch, NonStop OS, NuttX, OpenBSD, OpenStep, Orbis OS,
OS/2, OS/400, OS21, Plan 9, PlayStation Portable, QNX, Qubes OS, ReactOS,
Redox, RICS OS, Sailfish OS, SCO Unix, Serenity, SINIX-Z, Solaris, SunOS,
Syllable OS, Symbian, Tizen, TPF, Tru64, tvOS, ucLinux, Ultrix, UNICOS,
UnixWare, VMS, vxWorks, WebOS, Wii system software, Windows, Windows CE, Xbox
System, z/OS, z/TPF, z/VM, z/VSE

Disabling cURL’s certificate checks

By default, cURL checks certificates when it connects over HTTPS. However, it is often useful to disable the certificate checking, when you are trying to make requests to sites using self-signed certificates, or if you need to test a site that has a misconfigured certificate.

To disable certificate checks, use the  certificate. We will test this by making a request to expired.badssl.com, which is a website using an expired SSL certificate.

curl -k https://expired.badssl.com/

With the  option, the certificate checks are ignored. So, cURL downloads the page and displays the request body successfully. On the other hand, if you didn’t use the  option, you will get an error, similar to the one below:

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector