Thought I’d write exactly what I did (Windows 10, 64-bit):
From the download page https://curl.haxx.se/download.html choose the download wizard https://curl.haxx.se/dlwiz/
Choose curl executable.
Choose Win64.
Choose generic.
Choose any.
Choose x86_64.
Choose the first recommended option. For me this was:
curl version: 7.53.1 — SSL enabled SSH enabled. Provided by: Viktor Szakáts. This package is type curl executable You will get a pre-built ‘curl’ binary from this link (or in some cases, by using the information that is provided at the page this link takes you). You may or may not get ‘libcurl’ installed as a shared library/DLL.
The file is packaged using 7zip. 7zip is a file archiving format.
Click download.
You should have the file curl-7.53.1-win64-mingw.7z in your downloads folder.
Install 7-Zip if you don’t have it.
Right-click, 7-Zip, Extract Here. Copy and paste the extracted file somewhere like Z:Tools
If you look in the bin folder you’ll see curl.exe. If you double-click it a window will quickly flash up and vanish. To run it you need to use the Command Prompt. Navigate to the bin folder and type curl followed by your parameters to make a request. You must use double-quotes. Single quotes won’t work with curl on Windows.
Now you’ll want to add curl to a user’s Path variable so you don’t have to navigate to the right folder to run the program. Go to This PC, Computer, System Properties, Advanced system settings, authenticate as an administrator (you’re not running as admin, right? Right?) Environment Variables, System variables, look at the list and select Path, then Edit, then New, then, e.g.
Z:Toolscurl-7.53.1-win64-mingwbin
You can add a trailing backslash if you like, I don’t think it matters. Click move up until it’s at the top of the list, then you can see it easily from the previous screen. Click OK, OK, OK, then crack open a Command Prompt and you can run curl by typing curl from any folder, as any user. Don’t forget your double-quotes.
This is the answer I wish I’d had.
Curl (client URL) — это инструмент командной строки на основе библиотеки libcurl для передачи данных с сервера и на сервер при помощи различных протоколов, в том числе HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP и SMTPS. Он очень популярен в сфере автоматизации и скриптов благодаря широкому диапазону функций и поддерживаемых протоколов. В этой статье мы расскажем, как использовать curl в Windows на различных примерах.
▍ Установка в Windows
Во всех современных версиях Windows, начиная с Windows 10 (версия 1803) и Server 2019, исполняемый файл curl поставляется в комплекте, поэтому ручная установка не требуется. Чтобы определить местоположение curl и его версию в системе, можно использовать следующие команды:
where curl
curl --version
Определение местоположения и версии curl в Windows
Команда curl —version также выводит список протоколов и функций, поддерживаемых текущей версией curl. Как видно из показанного выше скриншота, к использованию встроенной утилиты curl всё готово. Если вместо этого отображается сообщение об ошибке, curl может быть недоступен потому, что вы используете более раннюю версию Windows (например, Windows 8.1 или Server 2016). В таком случае вам потребуется установить curl в Windows вручную.
▍ Синтаксис curl
Команда curl использует следующий синтаксис:
curl [options...] [url]
Инструмент поддерживает различные опции, которые мы рассмотрим ниже. Как и в любом инструменте командной строки, вы можете использовать для получения справки команду curl —help.
Получение справки при помощи команды curl
Для получения подробной справки можно использовать команду curl —help all. Справка разделена на категории, поэтому при помощи curl —help category можно просмотреть все темы.
Ознакомившись с синтаксисом curl, давайте рассмотрим различные способы применения этого инструмента на примерах.
▍ HTTP-запрос GET
При использовании curl с URL и без указания опций запрос по умолчанию использует метод GET протокола HTTP. Попробуйте выполнить такую команду:
curl https://4sysops.com
Приведённая выше команда по сути эквивалентна curl —request GET 4sysops.com, отправляющей запрос GET к 4sysops.com по протоколу HTTPS. Чтобы указать версию протокола HTTP (например, http/2), используйте опцию —http2:
curl --http2 https://4sysops.com
В случае URL, начинающихся с HTTPS, curl сначала пытается установить соединение http/2 и автоматически откатывается к http/1.1, если это не удаётся. Также он поддерживает другие методы, например, HEAD, POST, PUT и DELETE. Для использования этих методов вместе с командой curl нужно указать опцию —request (или -X), за которой следует указание метода. Стоит заметить, что список доступных методов зависит от используемого протокола.
▍ Получение информации об удалённом файле
Если вы администратор, то иногда вам могут быть интересны только заголовки HTTP. Их можно получить при помощи опции —head (или -I). Иногда URL может перенаправлять пользователя в другую точку. В таком случае опция —location (или -L) позволяет curl выполнять перенаправления. Также можно использовать —insecure (или -k), чтобы разрешить незащищённые подключения и избежать ошибок с сертификатом TLS в случае, если целевой URL использует самоподписанный сертификат. Пользуйтесь этой опцией только при абсолютной необходимости. Все эти три опции можно скомбинировать в одну краткую запись, как показано в следующей команде:
curl -kIL 4sysops.com
Опции просмотра заголовков запросов, включения незащищённого соединения и использования перенаправлений
Как можно заметить, такая краткая запись особенно полезна для комбинирования нескольких опций. Приведённая выше команда по сути эквивалентна команде curl —insecure —head —location 4sysops.com.
Опция —head (или -I) также даёт основную информацию об удалённом файле без его скачивания. Как показано на скриншоте ниже, при использовании curl с URL удалённого файла он отображает различные заголовки, дающие информацию об удалённом файле.
curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip
Использование curl для просмотра основной информации удалённых файлов
Заголовок Content-Length обозначает размер файла (в байтах), Content-Type сообщает о типе медиафайла (например, image/png, text/html), Server обозначает тип серверного приложения (Apache, Gunicorn и так далее), Last-Modified показывает дату последнего изменения файла на сервере, а заголовок Accept-Ranges обозначает поддержку частичных запросов для скачивания от клиента, что по сути определяет возможность продолжения прерванной загрузки.
▍ Скачивание файла
Для скачивания файла и сохранения с тем же именем, что и на сервере, можно использовать curl с опцией —remote-name (или -O). Показанная ниже команда скачивает последнюю версию curl для Windows с официального сайта:
curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла с именем по умолчанию и индикатором прогресса
При необходимости для нахождения ресурса добавляется опция -L, разрешающая перенаправления. Если нужно сохранить файл с новым именем, используйте опцию —output (или -o). Кроме того, при использовании команды curl в скрипте может понадобиться отключить индикатор прогресса, что можно сделать при помощи опции —silent (или -s). Эти две опции можно скомбинировать:
curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла без индикатора и сохранение под произвольным именем
▍ Продолжение прерванного скачивания
Наличие Accept-Ranges: bytes в заголовке ответа в буквальном смысле обозначает, что сервер поддерживает скачивания с возможностью продолжения. Чтобы продолжить прерванное скачивание, можно использовать опцию —continue-at (или -C), получающую смещение (в байтах). Обычно указывать смещение непросто, поэтому curl предоставляет простой способ продолжения прерванной загрузки:
curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso
Продолжение прерванного скачивания
Как видно из скриншота, я скачивал iso-файл Ubuntu, но скачивание было прервано. Затем я снова запустил команду curl с опцией -C, и передача продолжилась с того диапазона байтов, на котором была прервана. Знак минус (—) рядом с -C позволяет curl автоматически определить, как и где продолжить прерванное скачивание.
▍ Аутентификация с Curl
Также Curl поддерживает аутентификацию, что позволяет скачать защищённый файл, предоставив учётные данные при помощи опции —user (or -u), принимающей имя пользователя и пароль в формате username:password. Если не вводить пароль, curl попросит ввести его в режиме no-echo.
curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip
Скачивание файла с аутентификацией по имени пользователя и паролю
Если вы используете Basic authentication, то необходимо передать имя пользователя и пароль, а значит, воспользоваться защищённым протоколом наподобие HTTPS (вместо HTTP) или FTPS (вместо FTP). Если по каким-то причинам приходится использовать протокол без шифрования, то убедитесь, что вы используете способ аутентификации, не передающий учётные данные в виде простого текста (например, аутентификацию Digest, NTLM или Negotiate).
Также curl поддерживает использование файлов конфигурации .curlrc, _curlrc и .netrc, позволяющих задавать различные опции curl в файле, а затем добавлять файл в команду при помощи опции curl —config (или curl -K), что особенно полезно при написании скриптов.
▍ Выгрузка файла
Опция —upload-file (или -T) позволяет выгружать локальный файл на удалённый сервер. Показанная ниже команда выгружает файл из локальной системы на удалённый веб-сервер по протоколу FTPS:
curl -kT C:UsersSurenderDownloadssample1.zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка файла на удалённый сервер
Опция -k добавляется для устранения проблем с сертификатами на случай, если веб-сервер использует самоподписанный сертификат. Наклонная черта в конце URL сообщает curl, что конечная точка является папкой. Можно указать несколько имён файлов, например «{sample1.zip,sample2.zip}». Ниже показано, как с помощью одной команды curl можно выгрузить на сервер несколько файлов:
curl -kT sample[1-5].zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка нескольких файлов на сервер
▍ Последовательность команд
Как говорилось ранее, curl поддерживает различные методы в зависимости от используемого протокола. Дополнительные команды можно отправлять при помощи —quote (или -Q) для выполнения операции до или после обычной операции curl. Например, можно скачать файл с удалённого сервера по протоколу FTPS и удалить файл с сервера после успешного скачивания. Для этого нужно выполнить следующую команду:
curl -u testlabsurender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"
Удаление файла после успешного скачивания
В показанном выше примере я скачал файл sample1.zip с FTPS-сервера при помощи опции -O. После опции -Q я добавил минус (-) перед командой DELE, что заставляет curl отправить команду DELE sample1.zip сразу после успешного скачивания файла. Аналогично, если вы хотите отправить команду на сервер до выполнения операции curl, используйте плюс (+) вместо минуса.
▍ Изменение user-agent
Информация user-agent сообщает серверу тип клиента, отправляющего запрос. При отправке запроса curl на сервер по умолчанию используется user-agent curl/<version>. Если сервер настроен так, чтобы блокировать запросы curl, можно задать собственный user-agent при помощи опции —user-agent (или -A). Показанная ниже команда отправляет стандартный user-agent Google Chrome:
curl -kIA "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0" https://awesomewebsite.com/files/secretFile.zip
Использование собственного user-agent с командой curl, чтобы избежать блокировки сервером
На показанном выше скриншоте видно, что обычный запрос curl был отклонён веб-сервером (с ответом 403 Forbidden), но при передаче другого user-agent запрос выполняется успешно, возвращая ответ 200 OK.
▍ Отправка куки
По умолчанию запрос curl не отправляет и не сохраняет куки. Для записи куки можно использовать опцию —cookie-jar (или -c), а отправить куки можно опцией —cookie (or -b):
curl -c /path/cookie_file https://awesomewebsite.com/
curl -b /path/cookie_file https://awesomewebsite.com/
Первая команда записывает файл куки, а вторая отправляет куки с запросом curl. Также можно отправить куки в формате ‘name = value’:
curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io
Отправка нескольких куки командой curl
Я воспользовался веб-сайтом echo.hoppscotch.io для демонстрации заголовков HTTP-запросов, которые обычно невидимы клиентам, отправляющим запрос. Если вы не хотите пользоваться этим веб-сайтом, то можете применить опцию –verbose (или -v) для отображения запроса в сыром виде (который отображает и заголовки запросов).
▍ Использование прокси-сервера
Если вы пользуетесь прокси-сервером для подключения к интернету, в curl можно указать прокси опцией —proxy (или -x). Если прокси-сервер требует аутентификации, то добавьте —proxy-user (или -U):
curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/
Прокси-сервер указывается в формате server:port, а пользователь прокси — в формате username:password. Можно не вводить пароль пользователя прокси, тогда curl попросит ввести его в режиме no-echo.
Использование прокси-сервера и аутентификации
▍ Дополнительные заголовки запросов
Иногда вместе с запросом к серверу необходимо отправить дополнительную информацию. В curl это можно сделать при помощи —header (или -H), как показано в следующей команде:
curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com
Указание дополнительных заголовков для запроса curl
Можно отправлять любую информацию, недоступную через стандартные заголовки HTTP-запросов. В этом примере я отправил название своей операционной системы. Также я добавил опцию -v для включения verbose-вывода, отображающего дополнительный заголовок, отправляемый вместе с каждым моим запросом curl.
▍ Отправка электронного письма
Так как curl поддерживает протокол SMTP, его можно использовать для отправки электронного письма. Показанная ниже команда позволяет отправить электронное письмо при помощи curl:
curl --insecure --ssl-reqd smtps://mail.yourdomain.com –-mail-from sender@yourdomain.com –-mail-rcpt receiver@company.com --user sender@yourdomain.com --upload-file email_msg.txt
Отправка электронного письма командой curl
Давайте вкратце перечислим использованные здесь опции:
- Опция —insecure (или -k) используется, чтобы избежать ошибки сертификата SSL. Мы уже применяли её ранее.
- Опция —ssl-reql используется для апгрейда соединения передачи простого текста до зашифрованного соединения, если оно поддерживается SMTP-сервером. Если вы уверены, что ваш SMTP-сервер поддерживает SSL, то можно использовать непосредственно имя сервера smtps (например, smtps://smtp.yourdomain.com), как показано на скриншоте.
- Опция —mail-from используется для указания адреса электронной почты отправителя.
- Опция mail-rcpt указывает адрес электронной почты получателя.
- Опция —user (или -u) отправляет имя пользователя для аутентификации, оно должно совпадать с адресом mail-from, потому что в противном случае письмо может быть отклонено или помечено как спам.
- Опция —upload-file (или -T) используется для указания файла, в котором находится отправляемое письмо.
На скриншоте ниже показано письмо, полученное мной во входящие:
Просмотр письма, отправленного с помощью curl
Это всего лишь несколько примеров использования curl — на самом деле их гораздо больше. Я настоятельно рекомендую проверить справку по curl и поэкспериментировать с ней.
А вы используете curl? И если да, то для чего?
Telegram-канал с полезностями и уютный чат
Curl (client URL) is a command-line tool powered by the libcurl library to transfer data to and from the server using various protocols, such as HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP, and SMTPS. It is highly popular for automation and scripts due to its wide range of features and protocol support. In this article, you will learn how to use curl in Windows with various examples. Let’s get started.
Contents
- Install curl on Windows
- Curl syntax
- HTTP GET request
- Get remote file information.
- Download a file
- Resume interrupted download
- Authentication with Curl
- Upload a file
- Quote a command
- Change the user-agent
- Send a cookie
- Use a proxy server
- Additional request headers
- Send an email
- Author
- Recent Posts
Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows Servers, Active Directory, PowerShell, web servers, networking, Linux, virtualization, and penetration testing. He loves writing for his blog.
Latest posts by Surender Kumar (see all)
- Extending LVM space in Ubuntu — Thu, Feb 2 2023
- Backup in Proxmox VE — Thu, Jan 26 2023
- Snapshots in Proxmox VE — Wed, Jan 25 2023
Install curl on Windows
All the modern Windows versions, starting with Windows 10 (version 1803) and Server 2019, have the curl executable pre-installed, so there is no need for a manual installation. To determine the curl location and version in your system, you can use the following commands:
where curl curl --version
Determine the location and version of curl in Windows
The curl —version command also lists the protocols and features supported by the current curl version. If you see an output, as shown in the screenshot above, you’re all set to use the built-in curl utility. If you get an error message instead, curl might not be available, probably because you’re on an earlier version of Windows (e.g., Windows 8.1 or Server 2016). In that case, you might need to manually setup curl in Windows.
Curl syntax
The curl command uses the following syntax:
curl [options...] [url]
It supports various options, which we will discuss later in this post. As with any other command-line tool, you can use the curl —help command to get help.
Getting help with the curl command
To get detailed help, you can use curl —help all. The help section is divided into categories, so the curl —help category gets you an overview of all the categories.
Now that you’ve become familiar with curl syntax, let’s discuss various use cases with the help of examples.
HTTP GET request
When you use curl against a URL without specifying any option, the request defaults to the GET method of the HTTP protocol. Try this:
curl https://4sysops.com
The above command is essentially equivalent to curl —request GET https://4sysops.com, which sends a GET request to 4sysops.com using the HTTPS protocol. To specify the HTTP protocol version (e.g., http/2), use the —http2 option, as shown below:
curl --http2 https://4sysops.com
For URLs starting with HTTPS, curl first tries to negotiate to establish a http/2 connection and automatically falls back to http/1.1 if the negotiation fails. It also supports other methods, such as HEAD, POST, PUT, and DELETE. To use these methods, along with the curl command, use the —request (or -X) option, followed by the method. Notice that the methods that are available depend on the protocol being used.
Get remote file information.
As an admin, you might want to be interested in HTTP headers only. This can be done using the —head (or -I) option. Sometimes, a URL might redirect you to another location. In that case, —location (or -L) allows the curl to follow the redirects. You can also use —insecure (or -k) to allow insecure connections to avoid any TLS certificate errors if the target URL is using a self-signed certificate. Use this only when absolutely necessary. All three of these options can be combined in short-notation, as shown in the following command:
curl -kIL 4sysops.com
View request headers allow insecure connection and follow redirect options with curl
You can see that short-notation is particularly useful for combining multiple options. The above command is essentially equivalent to the curl —insecure —head —location 4sysops.com command.
The —head (or -I) option also gives you basic information about a remote file without actually downloading it. As shown in the screenshot below, when you use curl with a remote file URL, it displays various headers to give you information about the remote file.
curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip
Use curl to view the basic information about remote files
The Content-Length header indicates the size of the file (in bytes), Content-Type reveals the media type of the file (for instance image/png, text/htm), Server indicates the type of server application (Apache, Gunicron, etc.), Last-Modified shows the date when file was last changed on the server, and the Accept-Ranges header indicates the support of partial requests from the client for downloads, which essentially means you can resume an interrupted download.
Download a file
You can use curl with the —remote-name option (or -O, in short) to download a file and save it with the same name as on the server. The following command downloads the latest version of curl for Windows from the official website:
curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Downloading a file with a default name and progress indicator using curl
The -L option is added to follow redirects, if needed, for locating the resource. If you want to save the file with a new name, use the —output (or -o) option instead. Furthermore, while using the curl command in a script, you might want to suppress the progress indicator using —silent (or -s). Both options can be combined, as shown in the following command:
curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Silently download a file and save with a custom name using curl
Resume interrupted download
The presence of Accept-Ranges: bytes in the response header literally means that the server supports resumable downloads. To resume an interrupted download, you can use —continue-at (or -C), which accepts an offset (in bytes). Generally, specifying an offset is tricky, so curl offers an easy way of resuming an interrupted download:
curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso
Resuming an interrupted download with curl
As you can see in the screenshot, I was downloading an Ubuntu iso file, which was interrupted. When I ran the curl command again with the -C option, the transfer was resumed from the byte range where it was interrupted. The minus sign (—) next to -C allows the curl to automatically figure out how and where to resume the interrupted download.
Authentication with Curl
Curl also supports authentication, allowing you to download a protected file by supplying credentials with the —user (or -u) option, which accepts a username and password in the username:password format. If you skip typing the password, curl will prompt you to type it in no-echo mode.
curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip
Downloading a file using username and password authentication with curl
If you use a basic authentication method, you have to transfer a username and password, which means that you should use a secure protocol such as HTTPS (instead of HTTP) or FTPS (instead of FTP). If, for some reason, you have to use an unencrypted protocol, make sure you use an authentication method that doesn’t transmit credentials in clear text (for instance, Digest, NTLM, or Negotiate authentication).
Curl also supports the use of .curlrc, _curlrc, and .netrc config files, allowing you to define various curl options in a file and then to include the file in your command with curl —config (or curl -K), which is particularly useful for scripting.
Upload a file
The —upload-file (or -T) option allows you to upload a local file to a remote server. The following command shows how to upload a file from a local system to a remote web server using the FTPS protocol:
curl -kT C:UsersSurenderDownloadssample1.zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Uploading a file to a remote server using curl
The -k option is included to avoid certificate errors if the web server uses a self-signed certificate. The trailing slash at the end of the URL tells curl that the destination is a directory. You could specify multiple file names, such as “{sample1.zip,sample2.zip}.” The following command shows how to upload multiple files with a single curl command:
curl -kT sample[1-5].zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Upload multiple files to a remote server using curl
Quote a command
As already discussed, curl supports various methods based on the underlying protocol being used. You can send additional commands using —quote (or -Q) to perform a particular operation either before or after the regular curl operation; for instance, if you want to download a file from a remote server using the FTPS protocol and want the file to be removed from the server once it has been downloaded successfully. To do this, you can run the command shown below:
curl -u testlabsurender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"
Delete a file after successful download using curl command
Here, I downloaded the sample1.zip file from an FTPS server with the help of the -O option. After the -Q option, I added a minus sign (-) just before the DELE command, which tells the curl to send the DELE sample1.zip command immediately after the file is downloaded successfully. Likewise, if you want to send a command to the server before performing the actual curl operation, use a plus (+) sign instead of a minus sign.
Change the user-agent
The user-agent tells a server what type of client is sending the request. When you send a curl request to the server, the curl/<version> user-agent is used by default. If the server is configured to block the curl requests, you can specify a custom user-agent using —user-agent (or -A). The following command sends a common Google Chrome user-agent:
curl -kIA "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0" https://awesomewebsite.com/files/secretFile.zip
Use a custom user agent with a curl command to avoid server blocks
The above screenshot shows that a normal curl request was forbidden by the web server (with a 403 Forbidden response), but when I passed a custom user-agent, the request was successful, returning a 200 OK response.
Send a cookie
By default, the curl request does not send or store cookies. To write a cookie, use the —cookie-jar (or -c) option, and with —cookie (or -b), you can send a cookie:
curl -c /path/cookie_file https://awesomewebsite.com/ curl -b /path/cookie_file https://awesomewebsite.com/
The first command writes a cookie file, and the second command sends the cookie with a curl request. You can also send a cookie in ‘name = value’‘ format, as shown below:
curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io
Send multiple cookies using a curl command
I used the echo.hoppscotch.io website to view HTTP request headers that aren’t normally visible to clients sending a request. If you don’t want to use this website, you could use the –verbose (or -v) option to see your request in raw form (which will show request headers, too).
Use a proxy server
Do you use a proxy server to connect to the internet? No problem! Curl lets you specify a proxy server using the —proxy (or -x) option. If your proxy server requires authentication, add —proxy-user (or -U):
curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/
The proxy server is specified in the server:port format, and the proxy user is specified in the username:password format. Again, you could skip typing the password for the proxy user, and curl will prompt you to enter it in no-echo mode.
Use a proxy server and authentication with a curl command
Additional request headers
Sometimes, you might want to send additional information along with your request to the server. With curl, you can do so easily by using —header (or -H), as shown in the following command:
curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com
Specify additional headers with a curl request
You could send any information that isn’t available with standard HTTP request headers. In this example, I sent my operating system name. I also added the -v option this time to enable verbose output, which displayed the additional header being sent along with my curl request.
Send an email
Since curl supports the SMTP protocol, you could use it to send an email message. The following command shows how to send an email using curl:
curl --insecure --ssl-reqd smtps://mail.yourdomain.com –-mail-from sender@yourdomain.com –-mail-rcpt receiver@company.com --user sender@yourdomain.com --upload-file email_msg.txt
Send an email message using a curl command
Let’s quickly discuss the options used:
- The —insecure (or -k) command is used to avoid an SSL certificate error. We have used this before.
- The —ssl-reql option is used to upgrade a plain-text connection to encrypted connection if supported by the SMTP server. Alternatively, if you’re sure your SMTP server supports SSL, you could directly use the smtps server name (e.g., smtps://smtp.yourdomain.com), as you can see in the screenshot.
- The —mail-from option is used to define the sender’s (from) email address.
- The mail-rcpt option specifies the recipient’s email address.
- The —user (or -u) option sends the username for authentication, which should match the mail-from address, because otherwise your message might be rejected or flagged as spam.
- The —upload-file (or -T) option is used to specify a file that contains the email message to send.
The following screenshot shows the email message I received in my inbox:
Viewing the email message sent with curl
Viewing the email message sent with curl
Subscribe to 4sysops newsletter!
These are just a few examples, but there is a lot more you can do with curl. I highly recommend checking out curl help and experimenting with it. You’ll notice what a powerful command curl is.
This article describes how to install and use CURL on Windows. Curl is a free command line utility used for transferring files using various protocols. Most commonly it is used for transferring files over HTTP(S).
cURL comes natively installed on Unix based operating systems such as MacOS and Linux. But windows is left out. Now that we have PowerShell on windows, you can get some of the functionality of cURL using various cmdlets like invoke-webrequest. However, if you are used to using a Unix toolset, you will be left wondering where you can find cURL.
Methods of Installing cURL
To install cURL on windows, you have five real options:
- Install using Chocolatey ( Windows Package manager)
- Download pre-compiled Binaries
- Compile from source code
- Install Cygwin
- Install Windows Subsystem for Linux (WSL)
In the next few sections, we will discuss each of the above installation methods.
Chocolatey Package Manager
If you want to go the Chocolatey route, it is really simple, just run:
choco install curl -y
This will install cURL for you. However, you need to first install the Chocolatey package manager. You can find instructions on how to install Chocolatey here.
Download Pre-Compiled cURL Binaries
cURL is supported on many platforms. And if you navigate here, you will see binaries you can download for many different platforms. All the way at the bottom of the page you will find the windows builds. They are all labeled as Win32 or Win64
I recommend you download the zip file in the Win64 – Generic section:
After you have downloaded and extracted the zip file, look in the src folder, you will find curl.exe. Copy curl.exe into your C:windowssystem32 folder. I choose this folder because it includes all of the other system utilities. And it is already part of your PATH variable, so you don’t have to do anything to add it.
Compile from Source Code
This is the hardest method of installation. If you are trying to get things up quickly, you should skip over this section. But, for those who want to do it just for the experience, or those who absolutely need the latest version, building from source code might be the method for you. You can find instructions on how to install from source code here: https://curl.haxx.se/docs/install.html
Install CYGWIN
CYGWIN is a Unix-like environment for Windows. You can’t natively run all of your favorite Unix tools on Windows. First, you have to download the source code and compile it to run on windows. Just like in the previous section. CYGWIN is a project where someone has gone through the work to pre-compile many of your favorite Unix tools for you.
To use cURL as part of CYGWIN, you first download and CYGWIN installer from here. While you are going through the installer, you will encounter a list of packages you wish to install. Make sure you select the cURL package.
Install Windows Subsystem for Linux (WSL)
Starting with Windows 10, Microsoft has released a product called Windows Subsystem for Linux (WSL). WSL gives you the bash command shell on windows, which is the same shell that runs on Linux/Unix. Installing WSL gives you a full Linux environment, unlike CYGWIN which is simply a collection of Unix utilities. WSL is based on Ubuntu Linux. So you will have tools like apt-get to install programs etc…. The main limitation of WSL is you don’t have a GUI. But that is fine for our purposes today.
Older builds of Windows 10 will have to enable Developer mode before they can install the windows feature. You can find instructions on how to do that here.
Starting with the windows 10 Fall Creators update, you don’t have to enable Developer mode. However, it is still a two-step process. First, you enable the windows feature. Then you install the Linux distribution from the windows store. instructions can be found here.
After you have installed WSL, go to your Start menu, click on Bash, and you can use all of your favorite Linux tools, including cURL.
As this guide is about installing cURL, I won’t go into great detail about using curl. However, here are some basics. Each of these commands will largely work the same way on both Windows and Unix variants.
First, you need to launch the appropriate command line environment. If you installed WSL or CYGWIN, you will need to go to your start menu and launch CYGWIN or BASH. Otherwise, you can launch a command prompt or Powershell window.
Next, type:
curl —help
The above command will show you all the different command arguments you can pass to cURL. This will be very important as you are learning how to use the tool.
Lets try pulling down the text of a webpage using curl with the following command:
curl http://54.184.76.36
You should see all the HTML code from idkrtm.com scroll by…that means it is working.
How to download website headers with curl
Next, let’s just pull down the headers. This is useful for just checking if a web page is working. If you’re on Linux, OSX/MacOS, CYGWIN, or WSL, the command would be:
curl -s -D - http://54.184.76.36 -o /dev/null
the output should be similar to this:
HTTP/1.1 200 OKDate: Mon, 12 Feb 2018 15:25:35 GMTServer: ApacheX-Powered-By: PHP/5.5.38Link: ; rel=”https://api.w.org/”, ; rel=shortlinkTransfer-Encoding: chunkedContent-Type: text/html; charset=UTF-8
On Windows Powershell, the same command would be:
curl -s -D - http://54.184.76.36 -o $null
Or on Windows CMD, the same command would be:
curl -s -D – http://54.184.76.36 -o nul
cURL Post request
When you make post requests, there are three kinds of posts you will probably make
- Post Variables
- Post a file
- Post JSON
For these three operations, we will need the -d, -x and -h CLI arguments. Here is an example of how we would post variables
curl -d "key1=value1&key2=value2" -X POST http://localhost
In the above example, we start by calling the curl command, then using the -d argument for data. Within the quotes, we pass in the 2 URL parameters we want to pass to the server. We then use the -X argument to tell cURL that we are going to make a post. Then we pass in the URL of the server we want to post to.
In the next example, we will post a file to the same URL
curl -d "@myfile.txt" -X POST http://localhost
This example is very similar to the original example. We use the same -d and -X arguments. But within the quotes we used @myfile.txt . This will upload myfile.txt from the current working directory and post it to the URL we specified
In the next example, we will pass in JSON to the same endpoint. You will notice in this example, we are passing in the -H parameter.
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost
You can see this is very similar to the previous two examples. However, we passed in JSON within the quotes, and we added a Content-Type:application/json header to the input. We did not have to do this in the previous examples, because the other examples were able to use the default content type: “Content-Type: application/x-www-form-urlencoded”
As you can imagine, the JSON you pass in can get quite large, so you can also pass in a JSON file
curl -d "@myfile.json" -X POST http://localhost
cURL Post request
As you are interacting with websites, it is only a matter of time before you encounter one where you need to authenticate. Similar to how you authenticate in your browser. cURL supports a variety of authentication methods, but today we will only cover basic authentication, which is very easy. See the example below.
curl -u myusername:mypassword http://localhost
In the above example, we added a -u parameter for username. We then separated the username from the password with a colon.
Summary
Thank you for stopping by today. We discussed five different ways to install cURL on your windows computer. And some of the most common commands you might need to use with cURL.
As you can see, cURL is a very flexible tool that can work on both Windows and Unix variants of operating systems. If you want to know a lot more about cURL, there is a free book on GitHub, called Everything Curl, that goes into great detail about everything you want to know about cURL.
curl tutorial
Simple Usage
Get the main page from a web-server:
curl https://www.example.com/
Get a README file from an FTP server:
curl ftp://ftp.funet.fi/README
Get a web page from a server using port 8000:
curl http://www.weirdserver.com:8000/
Get a directory listing of an FTP site:
Get the definition of curl from a dictionary:
curl dict://dict.org/m:curl
Fetch two documents at once:
curl ftp://ftp.funet.fi/ http://www.weirdserver.com:8000/
Get a file off an FTPS server:
curl ftps://files.are.secure.com/secrets.txt
or use the more appropriate FTPS way to get the same file:
curl --ftp-ssl ftp://files.are.secure.com/secrets.txt
Get a file from an SSH server using SFTP:
curl -u username sftp://example.com/etc/issue
Get a file from an SSH server using SCP using a private key (not
password-protected) to authenticate:
curl -u username: --key ~/.ssh/id_rsa scp://example.com/~/file.txt
Get a file from an SSH server using SCP using a private key
(password-protected) to authenticate:
curl -u username: --key ~/.ssh/id_rsa --pass private_key_password
scp://example.com/~/file.txt
Get the main page from an IPv6 web server:
curl "http://[2001:1890:1112:1::20]/"
Get a file from an SMB server:
curl -u "domainusername:passwd" smb://server.example.com/share/file.txt
Download to a File
Get a web page and store in a local file with a specific name:
curl -o thatpage.html http://www.example.com/
Get a web page and store in a local file, make the local file get the name of
the remote document (if no file name part is specified in the URL, this will
fail):
curl -O http://www.example.com/index.html
Fetch two files and store them with their remote names:
curl -O www.haxx.se/index.html -O curl.se/download.html
Using Passwords
FTP
To ftp files using name and password, include them in the URL like:
curl ftp://name:passwd@machine.domain:port/full/path/to/file
or specify them with the -u
flag like
curl -u name:passwd ftp://machine.domain:port/full/path/to/file
FTPS
It is just like for FTP, but you may also want to specify and use SSL-specific
options for certificates etc.
Note that using FTPS://
as prefix is the implicit way as described in the
standards while the recommended explicit way is done by using FTP://
and
the --ssl-reqd
option.
SFTP / SCP
This is similar to FTP, but you can use the --key
option to specify a
private key to use instead of a password. Note that the private key may itself
be protected by a password that is unrelated to the login password of the
remote system; this password is specified using the --pass
option.
Typically, curl will automatically extract the public key from the private key
file, but in cases where curl does not have the proper library support, a
matching public key file must be specified using the --pubkey
option.
HTTP
Curl also supports user and password in HTTP URLs, thus you can pick a file
like:
curl http://name:passwd@machine.domain/full/path/to/file
or specify user and password separately like in
curl -u name:passwd http://machine.domain/full/path/to/file
HTTP offers many different methods of authentication and curl supports
several: Basic, Digest, NTLM and Negotiate (SPNEGO). Without telling which
method to use, curl defaults to Basic. You can also ask curl to pick the most
secure ones out of the ones that the server accepts for the given URL, by
using --anyauth
.
Note! According to the URL specification, HTTP URLs can not contain a user
and password, so that style will not work when using curl via a proxy, even
though curl allows it at other times. When using a proxy, you must use the
-u
style for user and password.
HTTPS
Probably most commonly used with private certificates, as explained below.
Proxy
curl supports both HTTP and SOCKS proxy servers, with optional authentication.
It does not have special support for FTP proxy servers since there are no
standards for those, but it can still be made to work with many of them. You
can also use both HTTP and SOCKS proxies to transfer files to and from FTP
servers.
Get an ftp file using an HTTP proxy named my-proxy that uses port 888:
curl -x my-proxy:888 ftp://ftp.leachsite.com/README
Get a file from an HTTP server that requires user and password, using the
same proxy as above:
curl -u user:passwd -x my-proxy:888 http://www.get.this/
Some proxies require special authentication. Specify by using -U as above:
curl -U user:passwd -x my-proxy:888 http://www.get.this/
A comma-separated list of hosts and domains which do not use the proxy can be
specified as:
curl --noproxy localhost,get.this -x my-proxy:888 http://www.get.this/
If the proxy is specified with --proxy1.0
instead of --proxy
or -x
, then
curl will use HTTP/1.0 instead of HTTP/1.1 for any CONNECT
attempts.
curl also supports SOCKS4 and SOCKS5 proxies with --socks4
and --socks5
.
See also the environment variables Curl supports that offer further proxy
control.
Most FTP proxy servers are set up to appear as a normal FTP server from the
client’s perspective, with special commands to select the remote FTP server.
curl supports the -u
, -Q
and --ftp-account
options that can be used to
set up transfers through many FTP proxies. For example, a file can be uploaded
to a remote FTP server using a Blue Coat FTP proxy with the options:
curl -u "username@ftp.server Proxy-Username:Remote-Pass"
--ftp-account Proxy-Password --upload-file local-file
ftp://my-ftp.proxy.server:21/remote/upload/path/
See the manual for your FTP proxy to determine the form it expects to set up
transfers, and curl’s -v
option to see exactly what curl is sending.
Piping
Get a key file and add it with apt-key
(when on a system that uses apt
for
package management):
curl -L https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
The ‘|’ pipes the output to STDIN. -
tells apt-key
that the key file
should be read from STDIN.
Ranges
HTTP 1.1 introduced byte-ranges. Using this, a client can request to get only
one or more sub-parts of a specified document. Curl supports this with the
-r
flag.
Get the first 100 bytes of a document:
curl -r 0-99 http://www.get.this/
Get the last 500 bytes of a document:
curl -r -500 http://www.get.this/
Curl also supports simple ranges for FTP files as well. Then you can only
specify start and stop position.
Get the first 100 bytes of a document using FTP:
curl -r 0-99 ftp://www.get.this/README
Uploading
FTP / FTPS / SFTP / SCP
Upload all data on stdin to a specified server:
curl -T - ftp://ftp.upload.com/myfile
Upload data from a specified file, login with user and password:
curl -T uploadfile -u user:passwd ftp://ftp.upload.com/myfile
Upload a local file to the remote site, and use the local file name at the
remote site too:
curl -T uploadfile -u user:passwd ftp://ftp.upload.com/
Upload a local file to get appended to the remote file:
curl -T localfile -a ftp://ftp.upload.com/remotefile
Curl also supports ftp upload through a proxy, but only if the proxy is
configured to allow that kind of tunneling. If it does, you can run curl in a
fashion similar to:
curl --proxytunnel -x proxy:port -T localfile ftp.upload.com
SMB / SMBS
curl -T file.txt -u "domainusername:passwd"
smb://server.example.com/share/
HTTP
Upload all data on stdin to a specified HTTP site:
curl -T - http://www.upload.com/myfile
Note that the HTTP server must have been configured to accept PUT before this
can be done successfully.
For other ways to do HTTP data upload, see the POST section below.
Verbose / Debug
If curl fails where it is not supposed to, if the servers do not let you in, if
you cannot understand the responses: use the -v
flag to get verbose
fetching. Curl will output lots of info and what it sends and receives in
order to let the user see all client-server interaction (but it will not show you
the actual data).
curl -v ftp://ftp.upload.com/
To get even more details and information on what curl does, try using the
--trace
or --trace-ascii
options with a given file name to log to, like
this:
curl --trace trace.txt www.haxx.se
Detailed Information
Different protocols provide different ways of getting detailed information
about specific files/documents. To get curl to show detailed information about
a single file, you should use -I
/--head
option. It displays all available
info on a single file for HTTP and FTP. The HTTP information is a lot more
extensive.
For HTTP, you can get the header information (the same as -I
would show)
shown before the data by using -i
/--include
. Curl understands the
-D
/--dump-header
option when getting files from both FTP and HTTP, and it
will then store the headers in the specified file.
Store the HTTP headers in a separate file (headers.txt in the example):
curl --dump-header headers.txt curl.se
Note that headers stored in a separate file can be useful at a later time if
you want curl to use cookies sent by the server. More about that in the
cookies section.
POST (HTTP)
It is easy to post data using curl. This is done using the -d <data>
option.
The post data must be urlencoded.
Post a simple name
and phone
guestbook.
curl -d "name=Rafael%20Sagula&phone=3320780" http://www.where.com/guest.cgi
How to post a form with curl, lesson #1:
Dig out all the <input>
tags in the form that you want to fill in.
If there is a normal post, you use -d
to post. -d
takes a full post
string, which is in the format
<variable1>=<data1>&<variable2>=<data2>&...
The variable names are the names set with "name="
in the <input>
tags, and
the data is the contents you want to fill in for the inputs. The data must
be properly URL encoded. That means you replace space with + and that you
replace weird letters with %XX
where XX
is the hexadecimal representation
of the letter’s ASCII code.
Example:
(page located at http://www.formpost.com/getthis/
)
<form action="post.cgi" method="post"> <input name=user size=10> <input name=pass type=password size=10> <input name=id type=hidden value="blablabla"> <input name=ding value="submit"> </form>
We want to enter user foobar
with password 12345
.
To post to this, you enter a curl command line like:
curl -d "user=foobar&pass=12345&id=blablabla&ding=submit"
http://www.formpost.com/getthis/post.cgi
While -d
uses the application/x-www-form-urlencoded mime-type, generally
understood by CGI’s and similar, curl also supports the more capable
multipart/form-data type. This latter type supports things like file upload.
-F
accepts parameters like -F "name=contents"
. If you want the contents to
be read from a file, use @filename
as contents. When specifying a file, you
can also specify the file content type by appending ;type=<mime type>
to the
file name. You can also post the contents of several files in one field. For
example, the field name coolfiles
is used to send three files, with
different content types using the following syntax:
curl -F "coolfiles=@fil1.gif;type=image/gif,fil2.txt,fil3.html"
http://www.post.com/postit.cgi
If the content-type is not specified, curl will try to guess from the file
extension (it only knows a few), or use the previously specified type (from an
earlier file if several files are specified in a list) or else it will use the
default type application/octet-stream
.
Emulate a fill-in form with -F
. Let’s say you fill in three fields in a
form. One field is a file name which to post, one field is your name and one
field is a file description. We want to post the file we have written named
cooltext.txt
. To let curl do the posting of this data instead of your
favorite browser, you have to read the HTML source of the form page and find
the names of the input fields. In our example, the input field names are
file
, yourname
and filedescription
.
curl -F "file=@cooltext.txt" -F "yourname=Daniel"
-F "filedescription=Cool text file with cool text inside"
http://www.post.com/postit.cgi
To send two files in one post you can do it in two ways:
Send multiple files in a single field with a single field name:
curl -F "pictures=@dog.gif,cat.gif" $URL
Send two fields with two field names
curl -F "docpicture=@dog.gif" -F "catpicture=@cat.gif" $URL
To send a field value literally without interpreting a leading @
or <
, or
an embedded ;type=
, use --form-string
instead of -F
. This is recommended
when the value is obtained from a user or some other unpredictable
source. Under these circumstances, using -F
instead of --form-string
could
allow a user to trick curl into uploading a file.
Referrer
An HTTP request has the option to include information about which address
referred it to the actual page. curl allows you to specify the referrer to be
used on the command line. It is especially useful to fool or trick stupid
servers or CGI scripts that rely on that information being available or
contain certain data.
curl -e www.coolsite.com http://www.showme.com/
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:
curl -A 'Mozilla/3.0 (Win95; I)' http://www.nationsbank.com/
Other common strings:
Mozilla/3.0 (Win95; I)
— Netscape Version 3 for Windows 95Mozilla/3.04 (Win95; U)
— Netscape Version 3 for Windows 95Mozilla/2.02 (OS/2; U)
— Netscape Version 2 for OS/2Mozilla/4.04 [en] (X11; U; AIX 4.2; Nav)
— Netscape for AIXMozilla/4.05 [en] (X11; U; Linux 2.0.32 i586)
— 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:
Konqueror/1.0
— KDE File Manager desktop clientLynx/2.7.1 libwww-FM/2.14
— Lynx command line browser
Cookies
Cookies are generally used by web servers to keep state information at the
client’s side. The server sets cookies by sending a response line in the
headers that looks like Set-Cookie: <data>
where the data part then
typically contains a set of NAME=VALUE
pairs (separated by semicolons ;
like NAME1=VALUE1; NAME2=VALUE2;
). The server can also specify for what path
the cookie should be used for (by specifying path=value
), when the cookie
should expire (expire=DATE
), for what domain to use it (domain=NAME
) and
if it should be used on secure connections only (secure
).
If you have received a page from a server that contains a header like:
Set-Cookie: sessionid=boo123; path="/foo";
it means the server wants that first pair passed on when we get anything in a
path beginning with /foo
.
Example, get a page that wants my name passed in a cookie:
curl -b "name=Daniel" www.sillypage.com
Curl also has the ability to use previously received cookies in following
sessions. If you get cookies from a server and store them in a file in a
manner similar to:
curl --dump-header headers www.example.com
… you can then in a second connect to that (or another) site, use the
cookies from the headers.txt
file like:
curl -b headers.txt www.example.com
While saving headers to a file is a working way to store cookies, it is
however error-prone and not the preferred way to do this. Instead, make curl
save the incoming cookies using the well-known Netscape cookie format like
this:
curl -c cookies.txt www.example.com
Note that by specifying -b
you enable the cookie engine and with -L
you
can make curl follow a location:
(which often is used in combination with
cookies). If a site sends cookies and a location field, you can use a
non-existing file to trigger the cookie awareness like:
curl -L -b empty.txt www.example.com
The file to read cookies from must be formatted using plain HTTP headers OR as
Netscape’s cookie file. Curl will determine what kind it is based on the file
contents. In the above command, curl will parse the header and store the
cookies received from www.example.com. curl will send to the server the stored
cookies which match the request as it follows the location. The file
empty.txt
may be a nonexistent file.
To read and write cookies from a Netscape cookie file, you can set both -b
and -c
to use the same file:
curl -b cookies.txt -c cookies.txt www.example.com
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:
% Total % Received % Xferd Average Speed Time Curr.
Dload Upload Total Current Left Speed
0 151M 0 38608 0 0 9406 0 4:41:43 0:00:04 4:41:39 9287
From left-to-right:
%
— percentage completed of the whole transferTotal
— total size of the whole expected transfer%
— percentage completed of the downloadReceived
— currently downloaded amount of bytes%
— percentage completed of the uploadXferd
— currently uploaded amount of bytesAverage Speed Dload
— the average transfer speed of the downloadAverage Speed Upload
— the average transfer speed of the uploadTime Total
— expected time to complete the operationTime Current
— time passed since the invokeTime Left
— expected time left to completionCurr.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 does not
need much explanation!
Speed Limit
Curl allows the user to set the transfer speed conditions that must be met to
let the transfer keep going. By using the switch -y
and -Y
you can make
curl abort transfers if the transfer speed is below the specified lowest limit
for a specified time.
To have curl abort the download if the speed is slower than 3000 bytes per
second for 1 minute, run:
curl -Y 3000 -y 60 www.far-away-site.com
This can be used in combination with the overall time limit, so that the above
operation must be completed in whole within 30 minutes:
curl -m 1800 -Y 3000 -y 60 www.far-away-site.com
Forcing curl not to transfer data faster than a given rate is also possible,
which might be useful if you are using a limited bandwidth connection and you
do not want your transfer to use all of it (sometimes referred to as
bandwidth throttle).
Make curl transfer data no faster than 10 kilobytes per second:
curl --limit-rate 10K www.far-away-site.com
or
curl --limit-rate 10240 www.far-away-site.com
Or prevent curl from uploading data faster than 1 megabyte per second:
curl -T upload --limit-rate 1M ftp://uploadshereplease.com
When using the --limit-rate
option, the transfer rate is regulated on a
per-second basis, which will cause the total transfer speed to become lower
than the given number. Sometimes of course substantially lower, if your
transfer stalls during periods.
Config File
Curl automatically tries to read the .curlrc
file (or _curlrc
file on
Microsoft Windows systems) from the user’s home dir on startup.
The config file could be made up with normal command line switches, but you
can also specify the long options without the dashes to make it more
readable. You can separate the options and the parameter with spaces, or with
=
or :
. Comments can be used within the file. If the first letter on a
line is a #
-symbol the rest of the line is treated as a comment.
If you want the parameter to contain spaces, you must enclose the entire
parameter within double quotes ("
). Within those quotes, you specify a quote
as "
.
NOTE: You must specify options and their arguments on the same line.
Example, set default time out and proxy in a config file:
# We want a 30 minute timeout:
-m 1800
# ... and we use a proxy for all accesses:
proxy = proxy.our.domain.com:8080
Whitespaces ARE significant at the end of lines, but all whitespace leading
up to the first characters of each line are ignored.
Prevent curl from reading the default file by using -q as the first command
line parameter, like:
Force curl to get and display a local help page in case it is invoked without
URL by making a config file similar to:
# default url to get
url = "http://help.with.curl.com/curlhelp.html"
You can specify another config file to be read by using the -K
/--config
flag. If you set config file name to -
it will read the config from stdin,
which can be handy if you want to hide options from being visible in process
tables etc:
echo "user = user:passwd" | curl -K - http://that.secret.site.com
Extra Headers
When using curl in your own programs, you may end up needing to pass on your
own custom headers when getting a web page. You can do this by using the -H
flag.
Example, send the header X-you-and-me: yes
to the server when getting a
page:
curl -H "X-you-and-me: yes" www.love.com
This can also be useful in case you want curl to send a different text in a
header than it normally does. The -H
header you specify then replaces the
header curl would normally send. If you replace an internal header with an
empty one, you prevent that header from being sent. To prevent the Host:
header from being used:
curl -H "Host:" www.server.com
FTP and Path Names
Do note that when getting files with a ftp://
URL, the given path is
relative to the directory you enter. To get the file README
from your home
directory at your ftp site, do:
curl ftp://user:passwd@my.site.com/README
If you want the README file from the root directory of that same site, you
need to specify the absolute file name:
curl ftp://user:passwd@my.site.com//README
(I.e with an extra slash in front of the file name.)
SFTP and SCP and Path Names
With sftp: and scp: URLs, the path name given is the absolute name on the
server. To access a file relative to the remote user’s home directory, prefix
the file with /~/
, such as:
curl -u $USER sftp://home.example.com/~/.bashrc
FTP and Firewalls
The FTP protocol requires one of the involved parties to open a second
connection as soon as data is about to get transferred. There are two ways to
do this.
The default way for curl is to issue the PASV command which causes the server
to open another port and await another connection performed by the
client. This is good if the client is behind a firewall that does not allow
incoming connections.
If the server, for example, is behind a firewall that does not allow
connections on ports other than 21 (or if it just does not support the PASV
command), the other way to do it is to use the PORT
command and instruct the
server to connect to the client on the given IP number and port (as parameters
to the PORT command).
The -P
flag to curl supports a few different options. Your machine may have
several IP-addresses and/or network interfaces and curl allows you to select
which of them to use. Default address can also be used:
curl -P - ftp.download.com
Download with PORT
but use the IP address of our le0
interface (this does
not work on Windows):
curl -P le0 ftp.download.com
Download with PORT
but use 192.168.0.10 as our IP address to use:
curl -P 192.168.0.10 ftp.download.com
Network Interface
Get a web page from a server using a specified port for the interface:
curl --interface eth0:1 http://www.example.com/
or
curl --interface 192.168.1.10 http://www.example.com/
HTTPS
Secure HTTP requires a TLS library to be installed and used when curl is
built. If that is done, curl is capable of retrieving and posting documents
using the HTTPS protocol.
Example:
curl https://www.secure-site.com
curl is also capable of using client certificates to get/post files from sites
that require valid certificates. The only drawback is that the certificate
needs to be in PEM-format. PEM is a standard and open format to store
certificates with, but it is not used by the most commonly used browsers. If
you want curl to use the certificates you use with your favorite browser, you
may need to download/compile a converter that can convert your browser’s
formatted certificates to PEM formatted ones.
Example on how to automatically retrieve a document using a certificate with a
personal password:
curl -E /path/to/cert.pem:password https://secure.site.com/
If you neglect to specify the password on the command line, you will be
prompted for the correct password before any data can be received.
Many older HTTPS servers have problems with specific SSL or TLS versions,
which newer versions of OpenSSL etc use, therefore it is sometimes useful to
specify what TLS version curl should use.:
curl --tlv1.0 https://secure.site.com/
Otherwise, curl will attempt to use a sensible TLS default version.
Resuming File Transfers
To continue a file transfer where it was previously aborted, curl supports
resume on HTTP(S) downloads as well as FTP uploads and downloads.
Continue downloading a document:
curl -C - -o file ftp://ftp.server.com/path/file
Continue uploading a document:
curl -C - -T file ftp://ftp.server.com/path/file
Continue downloading a document from a web server
curl -C - -o file http://www.server.com/
Time Conditions
HTTP allows a client to specify a time condition for the document it requests.
It is If-Modified-Since
or If-Unmodified-Since
. curl allows you to specify
them with the -z
/--time-cond
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:
curl -z local.html http://remote.server.com/remote.html
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:
curl -z -local.html http://remote.server.com/remote.html
You can specify a plain text date as condition. Tell curl to only download the
file if it was updated since January 12, 2012:
curl -z "Jan 12 2012" http://remote.server.com/remote.html
curl accepts a wide range of date formats. You always make the date check the
other way around by prepending it with a dash (-
).
DICT
For fun try
curl dict://dict.org/m:curl
curl dict://dict.org/d:heisenbug:jargon
curl dict://dict.org/d:daniel:gcide
Aliases for m
are match
and find
, and aliases for d
are define
and
lookup
. For example,
curl dict://dict.org/find:curl
Commands that break the URL description of the RFC (but not the DICT
protocol) are
curl dict://dict.org/show:db
curl dict://dict.org/show:strat
Authentication support is still missing
LDAP
If you have installed the OpenLDAP library, curl can take advantage of it and
offer ldap://
support. On Windows, curl will use WinLDAP from Platform SDK
by default.
Default protocol version used by curl is LDAP version 3. Version 2 will be
used as a fallback mechanism in case version 3 fails to connect.
LDAP is a complex thing and writing an LDAP query is not an easy task. I do
advise you to dig up the syntax description for that elsewhere. One such place
might be: RFC 2255, The LDAP URL Format
To show you an example, this is how I can get all people from my local LDAP
server that has a certain sub-domain in their email address:
curl -B "ldap://ldap.frontec.se/o=frontec??sub?mail=*sth.frontec.se"
If I want the same info in HTML format, I can get it by not using the -B
(enforce ASCII) flag.
You also can use authentication when accessing LDAP catalog:
curl -u user:passwd "ldap://ldap.frontec.se/o=frontec??sub?mail=*"
curl "ldap://user:passwd@ldap.frontec.se/o=frontec??sub?mail=*"
By default, if user and password are provided, OpenLDAP/WinLDAP will use basic
authentication. On Windows you can control this behavior by providing one of
--basic
, --ntlm
or --digest
option in curl command line
curl --ntlm "ldap://user:passwd@ldap.frontec.se/o=frontec??sub?mail=*"
On Windows, if no user/password specified, auto-negotiation mechanism will be
used with current logon credentials (SSPI/SPNEGO).
Environment Variables
Curl reads and understands the following environment variables:
http_proxy, HTTPS_PROXY, FTP_PROXY
They should be set for protocol-specific proxies. General proxy should be set
with
A comma-separated list of host names that should not go through any proxy is
set in (only an asterisk, *
matches all hosts)
If the host name matches one of these strings, or the host is within the
domain of one of these strings, transactions with that node will not be done
over proxy. When a domain is used, it needs to start with a period. A user can
specify that both www.example.com and foo.example.com should not use a proxy
by setting NO_PROXY
to .example.com
. By including the full name you can
exclude specific host names, so to make www.example.com
not use a proxy but
still have foo.example.com
do it, set NO_PROXY
to www.example.com
.
The usage of the -x
/--proxy
flag overrides the environment variables.
Netrc
Unix introduced the .netrc
concept a long time ago. It is a way for a user
to specify name and password for commonly visited FTP sites in a file so that
you do not have to type them in each time you visit those sites. You realize
this is a big security risk if someone else gets hold of your passwords,
therefore most Unix programs will not read this file unless it is only readable
by yourself (curl does not care though).
Curl supports .netrc
files if told to (using the -n
/--netrc
and
--netrc-optional
options). This is not restricted to just FTP, so curl can
use it for all protocols where authentication is used.
A simple .netrc
file could look something like:
machine curl.se login iamdaniel password mysecret
Custom Output
To better allow script programmers to get to know about the progress of curl,
the -w
/--write-out
option was introduced. Using this, you can specify what
information from the previous transfer you want to extract.
To display the amount of bytes downloaded together with some text and an
ending newline:
curl -w 'We downloaded %{size_download} bytesn' www.download.com
Kerberos FTP Transfer
Curl supports kerberos4 and kerberos5/GSSAPI for FTP transfers. You need the
kerberos package installed and used at curl build time for it to be available.
First, get the krb-ticket the normal way, like with the kinit
/kauth
tool.
Then use curl in way similar to:
curl --krb private ftp://krb4site.com -u username:fakepwd
There is no use for a password on the -u
switch, but a blank one will make
curl ask for one and you already entered the real password to kinit
/kauth
.
TELNET
The curl telnet support is basic and easy to use. Curl passes all data passed
to it on stdin to the remote server. Connect to a remote telnet server using a
command line similar to:
curl telnet://remote.server.com
And enter the data to pass to the server on stdin. The result will be sent to
stdout or to the file you specify with -o
.
You might want the -N
/--no-buffer
option to switch off the buffered output
for slow connections or similar.
Pass options to the telnet protocol negotiation, by using the -t
option. To
tell the server we use a vt100 terminal, try something like:
curl -tTTYPE=vt100 telnet://remote.server.com
Other interesting options for it -t
include:
XDISPLOC=<X display>
Sets the X display location.NEW_ENV=<var,val>
Sets an environment variable.
NOTE: The telnet protocol does not specify any way to login with a specified
user and password so curl cannot do that automatically. To do that, you need to
track when the login prompt is received and send the username and password
accordingly.
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 subsequent curl invokes. Try to stuff as many URLs as possible on the same
command line if they are using the same host, as that will make the transfers
faster. If you use an HTTP proxy for file transfers, practically all transfers
will be persistent.
Multiple Transfers With A Single Command Line
As is mentioned above, you can download multiple files with one command line
by simply adding more URLs. If you want those to get saved to a local file
instead of just printed to stdout, you need to add one save option for each
URL you specify. Note that this also goes for the -O
option (but not
--remote-name-all
).
For example: get two files and use -O
for the first and a custom file
name for the second:
curl -O http://url.com/file.txt ftp://ftp.com/moo.exe -o moo.jpg
You can also upload multiple files in a similar fashion:
curl -T local1 ftp://ftp.com/moo.exe -T local2 ftp://ftp.com/moo2.txt
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 --ipv4
and
--ipv6
options can specify which address to use when both are
available. IPv6 addresses can also be specified directly in URLs using the
syntax:
http://[2001:1890:1112:1::20]/overview.html
When this style is used, the -g
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 fe80::1234%1
,
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 --proxy
,
--interface
or --ftp-port
options) should not be URL encoded.
Mailing Lists
For your convenience, we have several open mailing lists to discuss curl, its
development and things relevant to this. Get all info at
https://curl.se/mail/.
Please direct curl questions, feature requests and trouble reports to one of
these mailing lists instead of mailing any individual.
Available lists include:
curl-users
Users of the command line tool. How to use it, what does not work, new
features, related tools, questions, news, installations, compilations,
running, porting etc.
curl-library
Developers using or developing libcurl. Bugs, extensions, improvements.
curl-announce
Low-traffic. Only receives announcements of new public versions. At worst,
that makes something like one or two mails per month, but usually only one
mail every second month.
curl-and-php
Using the curl functions in PHP. Everything curl with a PHP angle. Or PHP with
a curl angle.
curl-and-python
Python hackers using curl with or without the python binding pycurl.
cURL (client URL) is a command line tool that can be used to transfer data from a server. It is often used by developers to test web applications. cURL can be used to download files, submit form data, and even to login to websites.
The curl
command is one of the most used commands to automate the process of sending and receiving data to or from a server, and it provides a simple, easy-to-use command-line interface that can be used to do this.
The curl
command supports many protocols such as – HTTP, HTTPS, FTP, SFTP, TELNET, etc. It is a cross-platform tool available in Windows, Unix, and macOS.
cURL has a very broad usage – a quick way to see how broad of a usage, you can run curl -h
in your command line and see all of the options it offers.
Objectives
This tutorial will explain the basics of the cURL command and how to use it to transfer data to or from a server, along with some of it’s most frequently used options.
We’ll also explain the basics of HTTP requests and how to perform them with the cURL command, along with some useful things you can do.
Table of Contents
- Objectives
- Installing cURL on Your System
- Installing cURL on Debian-based Distros
- Installing cURL on RPM-based Distros
- Installing cURL on Windows
- Installing cURL on Mac OS X
- Basics of the cURL command
- Redirects with the cURL Command
- Use the -L Flag to Follow Redirects
- Save Outputs to A File with the cURL Command
- Downloading Multiple files
- Resuming Downloads
- Redirects with the cURL Command
- Basics of HTTP Requests & Responses
- HTTP Requests
- HTTP Responses
- HTTP Requests with The cURL Command
- GET Request With the cURL Command
- HEAD Request With the cURL Command
- Extract the HTTP Header
- Debugging with the HTTP Headers
- HTTP Header With the Redirect Option
- POST Requests With the cURL Command
- Sending Data Using POST Method
- Uploading Files with cURL
- Modify the HTTP Header
- PUT Requests With the cURL Command
- DELETE Requests With the cURL Command
- Conclusion
Installing cURL on Your System
If you’re using Linux, Mac OS X, or Windows 10 version 1803 or later, chances are cURL is already installed in your machine. You can check if you have cURL simply by typing the following in your command line:
curl -V
This will output the version of cURL, if it is installed:
Output
curl 7.68.0 (x86_64-pc-linux-gnu) libcurl/7.68.0 OpenSSL/1.1.1f zlib/1.2.11 brotli/1.0.7 libidn2/2.2.0 libpsl/0.21.0 (+libidn2/2.2.0) libssh/0.9.3/openssl/zlib nghttp2/1.40.0 librtmp/2.3 Release-Date: 2020-01-08 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp Features: AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets
You can also see the list of the supported protocols and the features. If you did not have cURL installed, you would’ve got something like this:
cURL not installed on Ubuntu 20.04
Command 'curl' not found, but can be installed with: sudo snap install curl # version 7.76.1, or sudo apt install curl # version 7.68.0-1ubuntu2.5 See 'snap info curl' for additional versions.
cURL not installed on Windows
'curl' is not recognized as an internal or external command, operable program or batch file.
If you don’t have cURL installed, next we’ll cover how to install it on your system.
Installing cURL on Debian-based Distros
To install cURL on Debian-based distros (Debian, Ubuntu etc.) run:
sudo apt-get update sudo apt-get install curl
Installing cURL on RPM-based Distros
To install cURL on RPM-based distros (CentOS, Fedora etc.) run:
sudo yum update sudo yum install curl
Installing cURL on Windows
There are multiple ways you can install cURL on Windows. We’ll focus on just one quick and clean way (in my opinion), which I hope works for most using Windows. If you encounter any issues please leave a comment and we’ll get back to you as soon as we can.
- Go to download page: Go to the curl Windows (https://curl.se/windows/)
- Download zip file: Click on curl for 64 bit or curl for 32 bit, to download the package, depending on which version you have. (Here is an article on Microsoft.com with a FAQ on 32-bit and 64-bit Windows, in case you need to check which one you have, along with a bit more info on the topic)
- Extract necessary files: It’s a a .zip archive. Double click to see the contents and go inside the
bin
folder. We wantcurl.exe
andcurl-ca-bundle.crt
. We’ll need to place them in some folder on our computer. You can create the folder anywhere and name it anything you want – I prefer to createC:Program Filescurl
and extract the two files in there. - Add cURL to
PATH
: We need to do this to be able to run the cURL command from anywhere in the command line. If we don’t do this, we’ll have to always navigate to wherecurl.exe
is located when we try to run it in the command line.What is thisPATH
? It’s an environment variable that specifies directories in which executables are located on the machine without knowing and typing the whole path to the file on the command line. To do this we need to find the Environment Variables section.
Installing cURL on Mac OS X
Mac OS X should come with the cURL command, but if it isn’t, we recommend installing it via Homebrew, a very popular package manager for Mac.
To install Homebrew open up the command line and run:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
The script should explain what it’s doing in the output.
When it’s finished, just run the following command to install cURL:
brew install curl
Basics of the cURL command
Now let’s move on to some basic usages of the cURL command.
The general structure of the curl
command looks like:
curl [options...] <url>
Let’s try the curl
command without any options:
curl https://example.com
This command will display the source code of example.com on your command line.
curl example.com
Let’s try another:
curl bytexd.com
curl bytexd.com
You may be surprised that there is no output. We’ll discuss this in the next section.
Redirects with the cURL Command
The curl
command without any options will use HTTP protocol by default. So, it will not perform any HTTPS redirects. As our website bytexd.com
uses HTTPS redirect, cURL cannot fetch the data over the HTTP protocol.
Now let’s try running the command again but this time we add https://
:
curl https://bytexd.com
Now you should get the expected result.
curl https://bytexd.com
Use the -L Flag to Follow Redirects
This is a good time to learn about the redirect option with the curl command:
curl -L bytexd.com
Notice how we didn’t have to specify https://
like we did previously.
The -L
flag or --location
option follows the redirects. Use this to display the contents of any website you want. By default, the curl command with the -L
flag will follow up to 50 redirects.
curl -L bytexd.com
Save Outputs to A File with the cURL Command
Now that you know how to display website content in your terminal, you may be wondering why anybody would want to do this. A bunch of HTML is indeed difficult to read when you’re looking at it in the command line.
But that’s where outputting them to a file becomes super helpful. You can save the file in different formats that’ll make them easier to read.
What can be even more useful is some cURL script pulling up content from the website and performing some tasks with the content automatically.
For now, let’s see how to save the output of the curl
command into a file:
curl -L -o file bytexd.com
The flag -o
or --output
will save the content of bytexd.com to the file.
You can open this file with your browser, and you’ll see the homepage of bytexd.com.
Now if the URL you used has some page with a name or some file you can use the -O
or --remote-name
flag to save the page/file with its original name. Let’s see this in action –
curl -O https://github.com/pbatard/rufus/releases/download/v3.14/rufus-3.14p.exe
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 619 100 619 0 0 3942 0 --:--:-- --:--:-- --:--:-- 3917
Here, I downloaded an executable file which is the Rufus tool. The file name will be rufus-3.14p.exe
.
So, the main difference between the -o
and -O
flag is that the -o
(lowercase) lets you save the file with a custom name.
Let’s understand this a bit more:
curl -L -O bytexd.com
curl -L -O bytexd.com
curl: Remote file name has no length! curl: try 'curl --help' or 'curl --manual' for more information
Now it’s clear that the -O
flag cannot be used where there is no page/filename. Whereas:
curl -L -O php.net/manual/en/tutorial.firstpage.php
This will generate the file tutorial.firstpage.php
which you can read.
Downloading Multiple files
You can download multiple files together using multiple -O
flags. Here’s an example where we download both of the files we used as examples previously:
curl -L -O https://github.com/pbatard/rufus/releases/download/v3.14/rufus-3.14p.exe -O php.net/manual/en/tutorial.firstpage.php
curl -L -O ..rufus-3.14p.exe -O ..tutorial.firstpage.php
Resuming Downloads
If you cancel some downloads midway, you can resume them by using the -C -
option:
curl -C - -O example.com/somefile.ext
With this, we’ve covered the basic cURL commands. Now we’ll move on to HTTP requests with cURL.
Basics of HTTP Requests & Responses
We need to learn some basics of the HTTP Requests & Responses
before we can perform them with the cURL command efficiently.
Notice: Even though we’re starting the basics of HTTP requests, you’ve already done some HTTP requests with the curl
command in previous sections. You’ll understand better to perform more commands after this section.
Whenever your browser is loading a page from any website, it performs HTTP requests. It is a client-server model.
- Your browser is the client here, and it requests the server to send back its content.
- The server provides the requested resources with the response.
The request your browser sent is called an HTTP request.
The response from the server is the HTTP response.
HTTP Requests
In the HTTP request-response model, the request is sent first.
These requests can be of different types which are called HTTP request methods.
The HTTP protocol establishes a group of methods that signals what action is required for the specific resources.
Let’s look at some of the HTTP request methods:
- GET Method: This request method does exactly as its name implies. It fetches the requested resources from the server. When a webpage is shown, the browser requests the server with this method.
- HEAD Method: This method is used when the client requests only for the HTTP Header. It does not retrieve other resources along with the header.
- POST Method: This method sends data and requests the server to accept it. The server might store it and use the data. Some common examples for this request method would be when you fill out a form and submit the data. This method would also be used when you’re uploading a photo, possibly a profile picture.
- PUT Method: This method is similar to the POST method, but it only affects the URI specified. It requests the server to create or replace the existing data. One key difference between this method and the post is that the PUT method always produces the same result when performed multiple times. The user decides the URI of the resource.
- DELETE Method: This method requests the server to delete the specified resources.
Now that you know some of the HTTP request methods, can you tell which request did you perform with the curl
command in the previous sections? The GET requests. We only requested the server to send the specified data and retrieved it.
We’ll shortly go through the ways to perform other requests with the cURL command. Let’s quickly go over the HTTP responses before that.
HTTP Responses
The server responds to the HTTP requests by sending back some responses.
The structure of the HTTP response is as follows:
- Status code: This is the first line of an HTTP response. See all the codes here. (Another way to remember status codes is by seeing each code associated with a picture of silly cats – https://http.cat)
- Response Header: The response will have a header section revealing some more information about the request and the server.
- Message Body: The response might have an additional message-body attached to it. It is optional. The message body is just below the Response Header, separated by an empty line.
Let’s take a look at an example HTTP response. We’ll use the cURL command to generate a GET request and see what response the server sends back:
curl -i example.com
Don’t worry about the -i
flag. It just tells the cURL command to show the response including the header.
Here is the response:
curl -i example.com
HTTP/1.1 200 OK Age: 525920 Cache-Control: max-age=604800 Content-Type: text/html; charset=UTF-8 Date: Sun, 16 May 2021 17:07:42 GMT Etag: "3147526947+ident" Expires: Sun, 23 May 2021 17:07:42 GMT Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT Server: ECS (dcb/7F81) Vary: Accept-Encoding X-Cache: HIT Content-Length: 1256 <!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-color: #f0f0f2; margin: 0; padding: 0; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; } div { width: 600px; margin: 5em auto; padding: 2em; background-color: #fdfdff; border-radius: 0.5em; box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); } a:link, a:visited { color: #38488f; text-decoration: none; } @media (max-width: 700px) { div { margin: 0 auto; width: auto; } } </style> </head> <body> <div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p> </div> </body> </html>
Can you break down the response?
The first line, which is highlighted, is the Status code. It means the request was successful, and we get a standard response.
Lines 2 to 12 represent the HTTP header. You can see some information like content type, date, etc.
The header ends before the empty line. Below the empty line, the message body is received.
Now you know extensive details about how the HTTP request and response work.
Let’s move on to learning how to perform some requests with the curl
command.
From this section, you’ll see different HTTP requests made by the cURL command. We’ll show you some example commands and explain them along the way.
GET Request With the cURL Command
By default, the cURL command performs the GET requests when no other methods are specified.
We saw some basic commands with cURL at the beginning of the article. All of those commands sent GET requests to the server, retrieved the data, and showed them in your terminal.
Here are some examples in the context of the GET requests:
curl example.com
As we mentioned before, the -L
flag enables the cURL command to follow redirects.
curl -L bytexd.com
Both will send GET requests to the servers specified.
HEAD Request With the cURL Command
We can extract the HTTP headers from the response of the server.
Why? Because sometimes you might want to take a look at the headers for some debugging or monitoring purposes.
The header is not shown when you perform GET requests with the cURL command.
For example, this command will only output the message body without the HTTP header.
curl example.com
To see only the header, we use the -I
flag or the --head
option.
curl -I example.com
It will output only the header section of the HTTP response.
Output
HTTP/1.1 200 OK Content-Encoding: gzip Accept-Ranges: bytes Age: 390829 Cache-Control: max-age=604800 Content-Type: text/html; charset=UTF-8 Date: Mon, 17 May 2021 19:33:52 GMT Etag: "3147526947" Expires: Mon, 24 May 2021 19:33:52 GMT Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT Server: ECS (dcb/7EEB) X-Cache: HIT Content-Length: 648
If you wanted to see the whole HTTP response, you’d use the -i
flag or --include
option as we mentioned earlier:
curl -i example.com
Now let’s find out why you might want to look at the headers. We’ll run the following command:
curl -I bytexd.com
Remember we couldn’t redirect to bytexd.com without the -L
flag? If you didn’t include the -I
flag there would’ve been no outputs.
With the -I
flag you’ll get the header of the response, which offers us some information:
HTTP/1.1 301 Moved Permanently Date: Thu, 13 May 2021 07:06:05 GMT Connection: keep-alive Cache-Control: max-age=3600 Expires: Thu, 13 May 2021 08:06:05 GMT Location: https://bytexd.com/ cf-request-id: 0a062512d2000001c88dbb2000000001 Report-To: {"endpoints":[{"url":"https://a.nel.cloudflare.com/report?s=U8B0HJ%2BLZ9xb%2FodQtDu1E0YCDElQ9%2FHpFJ0kuLX6tJRdY%2F4t9rAr9e2sdeEpTtnz%2FuBnOpyJj%2BjIm74ffdfhDExFFVkAKHoJDgu3"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 64ea0acaeed601c8-SIN alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
Look at the first line and you’ll see something interesting. It is the status code of your response. The code is 301 which indicates a redirect is necessary. As we mentioned before you can check HTTP status codes and their meanings here (Wikipedia) or here (status codes associated with silly cat pictures)
If you want to see the communication between cURL and the server then turn on the verbose option with the -v
flag:
curl -v bytexd.com
Output
* Trying 104.21.37.46:80... * TCP_NODELAY set * Connected to bytexd.com (104.21.37.46) port 80 (#0) > GET / HTTP/1.1 > Host: bytexd.com > User-Agent: curl/7.68.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 301 Moved Permanently < Date: Mon, 17 May 2021 19:40:57 GMT < Transfer-Encoding: chunked < Connection: keep-alive < Cache-Control: max-age=3600 < Expires: Mon, 17 May 2021 20:40:57 GMT < Location: https://bytexd.com/ < cf-request-id: 0a1d71998f00004108c090c000000001 < Report-To: {"endpoints":[{"url":"https://a.nel.cloudflare.com/report?s=y8EgEvrQ5VQuErysespUqCcmICva4jHOAap0Z1UKkT450FC4jcBLmAGOkyMcm2BhBnK7rRezgRwOOqffOIcCEJFH3zNQnO5vxy%2FO"}],"group":"cf-nel","max_age":604800} < NEL: {"report_to":"cf-nel","max_age":604800} < Server: cloudflare < CF-RAY: 650f5208ee5e4108-PRG < alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400 < * Connection #0 to host bytexd.com left intact
You can trace the whole request and response and save it to a file with the --trace
option:
curl --trace-ascii file.log bytexd.com
This is important for debugging and looking under the hood.
Now you might wonder what will happen if we use the redirect option -L
with the Header only -I
option. Let’s try it out:
curl -L -I bytexd.com
This will show the headers for all the HTTP responses for all the redirects. Previously we saw that without the -L
flag, the response only had one header. Now you’ll see two response headers.
The second one will have the status code of 200 OK which means Standard Response.
HTTP/1.1 301 Moved Permanently Date: Thu, 13 May 2021 07:26:16 GMT Connection: keep-alive Cache-Control: max-age=3600 Expires: Thu, 13 May 2021 08:26:16 GMT Location: https://bytexd.com/ cf-request-id: 0a06378cf60000ddbbac1c5000000001 Report-To: {"endpoints":[{"url":"https://a.nel.cloudflare.com/report?s=sBhAuyICvY79ULS0CZk3tMjz1y%2F%2BUiegyUCtTD7bojs1SXcXlGf26py8vLGXg%2Ba%2F%2FJAWgY2997sTMk4VS1qguJ3I%2F9IvKMe2TW7y"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 64ea285b28c7ddbb-SIN alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400 HTTP/1.1 200 OK Date: Thu, 13 May 2021 07:26:19 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive Vary: Accept-Encoding cf-edge-cache: cache,platform=wordpress Link: <https://bytexd.com/wp-json/>; rel="https://api.w.org/" X-Powered-By: WordOps X-Frame-Options: SAMEORIGIN X-Xss-Protection: 1; mode=block X-Content-Type-Options: nosniff Referrer-Policy: no-referrer, strict-origin-when-cross-origin X-Download-Options: noopen Strict-Transport-Security: max-age=31536000; includeSubDomains; preload X-fastcgi-cache: HIT CF-Cache-Status: DYNAMIC cf-request-id: 0a063793f1000001f6efa4e000000001 Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Report-To: {"endpoints":[{"url":"https://a.nel.cloudflare.com/report?s=vQ1vk%2BhP027gW2my981tBWMOTbmfpXYDwiJS%2BZExFsjw95qlyzHkFI2I1i3SdhuloGfDglCZRevbkdR8YdSNaD9C46KTz92qHqNd"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 64ea28664e4b01f6-SIN alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
Now let’s move on to the POST requests.
POST Requests With the cURL Command
We already mentioned that the cURL command performs the GET request method by default. For using other request methods need to use the -X
or --request
flag followed by the request method.
Let’s see an example:
curl -X [method] [more options] [URI]
For using the POST method we’ll use:
curl -X POST [more options] [URI]
Sending Data Using POST Method
You can use the -d
or --data
option with the curl
command to specify the data you want to send to the server.
This flag sends data with the content type of application/x-www-form-urlencoded
.
We’ll use httpbin.org/post
to send POST requests to. httpbin.org is free service HTTP request & response service and httpbin.org/post
accepts POST requests and will help us better understand how requests are made.
Here’s an example with the -d
flag:
curl -X POST -d "p1=value1" https://httpbin.org/post
This command will request the server to post the data p1=value1
. The p1
could be any parameter having any value. The URI is used just as an example here.
Multiple data can be sent like below:
curl -X POST -d 'p1=value1' -d 'p2=value1' https://httpbin.org/post
..or..
curl -X POST -d 'p1=value1&p2=value2' https://httpbin.org/post
Uploading Files with cURL
Multipart data can be sent with the -F
or --form
flag which uses the multipart/form-data or form content type.
You can also send files using this flag, and you’ll also need to attach the @
prefix to attach a whole file.
Replace /root/Desktop/file
with the path to any file on your computer that you want to test this command with.
curl -X POST -F '[email protected]/root/Desktop/file' https://httpbin.org/post
Upload multiple files by joining the strings representing the files to upload, joined by ;
:
curl -X POST -F '[email protected]/root/Desktop/file1;[email protected]/root/Desktop/file2' https://httpbin.org/post
..or by using multiple -F
flags:
curl -X POST -F '[email protected]/root/Desktop/file1' -F '[email protected]/root/Desktop/file2' https://httpbin.org/post
You can use the -H
or --header
flag to change the header content when sending data to a server. This will allow us to send custom-made requests to the server.
Specify the content type in the Header
We can specify the content type using this header.
Let’s send a JSON object with the application/json
content type:
curl -H 'Content-Type: application/json' -X POST -d '{"date": "18-May-2021", "name": "Ed"}' https://httpbin.org/post
PUT Requests With the cURL Command
The PUT
request will update or replace the specified content.
We’ll use httpbin.org/put
for testing.
Perform the PUT request by using the -X
flag:
curl -X PUT -d 'arg1=val1' -d 'arg2=val2' https://httpbin.org/put
We’ll show another example with the PUT method sending raw JSON data:
curl -X PUT -H "Content-Type: application/json" -d '{"name":"bytexd"}' https://httpbin.org/put
DELETE Requests With the cURL Command
You can request the server to delete some content with the DELETE
request method.
We’ll use httpbin.org/delete
for testing.
Here is the syntax for this request:
curl -X DELETE https://httpbin.org/delete
Let’s see what actually happens when we send a request like this. We can look at the status code by extracting the header:
curl -I -X DELETE https://httpbin.org/delete
HTTP/2 200 date: Mon, 17 May 2021 21:40:03 GMT content-type: application/json content-length: 319 server: gunicorn/19.9.0 access-control-allow-origin: * access-control-allow-credentials: true
Here we can see the status code is 200
which means the request was successful.
Conclusion
In this tutorial, we covered how to perform HTTP requests with the cURL command from the basics. You can learn more about the cURL command by typing man curl
in the terminal.
If you have any issues, questions or feedback, then feel free to contact us or leave a comment below, and we’ll get back to you as soon as possible.
Curl (client URL) — это инструмент командной строки на основе библиотеки libcurl для передачи данных с сервера и на сервер при помощи различных протоколов, в том числе HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP и SMTPS. Он очень популярен в сфере автоматизации и скриптов благодаря широкому диапазону функций и поддерживаемых протоколов. В этой статье мы расскажем, как использовать curl в Windows на различных примерах.
▍ Установка в Windows
Во всех современных версиях Windows, начиная с Windows 10 (версия 1803) и Server 2019, исполняемый файл curl поставляется в комплекте, поэтому ручная установка не требуется. Чтобы определить местоположение curl и его версию в системе, можно использовать следующие команды:
where curl
curl --version
Определение местоположения и версии curl в Windows
Команда curl —version также выводит список протоколов и функций, поддерживаемых текущей версией curl. Как видно из показанного выше скриншота, к использованию встроенной утилиты curl всё готово. Если вместо этого отображается сообщение об ошибке, curl может быть недоступен потому, что вы используете более раннюю версию Windows (например, Windows 8.1 или Server 2016). В таком случае вам потребуется установить curl в Windows вручную.
▍ Синтаксис curl
Команда curl использует следующий синтаксис:
curl [options...] [url]
Инструмент поддерживает различные опции, которые мы рассмотрим ниже. Как и в любом инструменте командной строки, вы можете использовать для получения справки команду curl —help.
Получение справки при помощи команды curl
Для получения подробной справки можно использовать команду curl —help all. Справка разделёна на категории, поэтому при помощи curl —help category можно просмотреть все темы.
Ознакомившись с синтаксисом curl, давайте рассмотрим различные способы применения этого инструмента на примерах.
▍ HTTP-запрос GET
При использовании curl с URL и без указания опций запрос по умолчанию использует метод GET протокола HTTP. Попробуйте выполнить такую команду:
curl https://4sysops.com
Приведённая выше команда по сути эквивалентна curl —request GET 4sysops.com, отправляющей запрос GET к 4sysops.com по протоколу HTTPS. Чтобы указать версию протокола HTTP (например, http/2), используйте опцию —http2:
curl --http2 https://4sysops.com
В случае URL, начинающихся с HTTPS, curl сначала пытается установить соединение http/2 и автоматически откатывается к http/1.1, если это не удаётся. Также он поддерживает другие методы, например, HEAD, POST, PUT и DELETE. Для использования этих методов вместе с командой curl нужно указать опцию —request (или -X), за которой следует указание метода. Стоит заметить, что список доступных методов зависит от используемого протокола.
▍ Получение информации об удалённом файле
Если вы администратор, то иногда вам могут быть интересны только заголовки HTTP. Их можно получить при помощи опции —head (или -I). Иногда URL может перенаправлять пользователя в другую точку. В таком случае опция —location (или -L) позволяет curl выполнять перенаправления. Также можно использовать —insecure (или -k), чтобы разрешить незащищённые подключения и избежать ошибок с сертификатом TLS в случае, если целевой URL использует самоподписанный сертификат. Пользуйтесь этой опцией только при абсолютной необходимости. Все эти три опции можно скомбинировать в одну краткую запись, как показано в следующей команде:
curl -kIL 4sysops.com
Опции просмотра заголовков запросов, включения незащищённого соединения и использования перенаправлений
Как можно заметить, такая краткая запись особенно полезна для комбинирования нескольких опций. Приведённая выше команда по сути эквивалентна команде curl —insecure —head —location 4sysops.com.
Опция —head (или -I) также даёт основную информацию об удалённом файле без его скачивания. Как показано на скриншоте ниже, при использовании curl с URL удалённого файла он отображает различные заголовки, дающие информацию об удалённом файле.
curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip
Использование curl для просмотра основной информации удалённых файлов
Заголовок Content-Length обозначает размер файла (в байтах), Content-Type сообщает о типе медиафайла (например, image/png, text/html), Server обозначает тип серверного приложения (Apache, Gunicorn и так далее), Last-Modified показывает дату последнего изменения файла на сервере, а заголовок Accept-Ranges обозначает поддержку частичных запросов для скачивания от клиента, что по сути определяет возможность продолжения прерванной загрузки.
▍ Скачивание файла
Для скачивания файла и сохранения с тем же именем, что и на сервере, можно использовать curl с опцией —remote-name (или -O). Показанная ниже команда скачивает последнюю версию curl для Windows с официального сайта:
curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла с именем по умолчанию и индикатором прогресса
При необходимости для нахождения ресурса добавляется опция -L, разрешающая перенаправления. Если нужно сохранить файл с новым именем, используйте опцию —output (или -o). Кроме того, при использовании команды curl в скрипте может понадобиться отключить индикатор прогресса, что можно сделать при помощи опции —silent (или -s). Эти две опции можно скомбинировать:
curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip
Скачивание файла без индикатора и сохранение под произвольным именем
▍ Продолжение прерванного скачивания
Наличие Accept-Ranges: bytes в заголовке ответа в буквальном смысле обозначает, что сервер поддерживает скачивания с возможностью продолжения. Чтобы продолжить прерванное скачивание, можно использовать опцию —continue-at (или -C), получающую смещение (в байтах). Обычно указывать смещение непросто, поэтому curl предоставляет простой способ продолжения прерванной загрузки:
curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso
Продолжение прерванного скачивания
Как видно из скриншота, я скачивал iso-файл Ubuntu, но скачивание было прервано. Затем я снова запустил команду curl с опцией -C, и передача продолжилась с того диапазона байтов, на котором была прервана. Знак минус (—) рядом с -C позволяет curl автоматически определить, как и где продолжить прерванное скачивание.
▍ Аутентификация с Curl
Также Curl поддерживает аутентификацию, что позволяет скачать защищённый файл, предоставив учётные данные при помощи опции —user (or -u), принимающей имя пользователя и пароль в формате username:password. Если не вводить пароль, curl попросит ввести его в режиме no-echo.
curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip
Скачивание файла с аутентификацией по имени пользователя и паролю
Если вы используете Basic authentication, то необходимо передать имя пользователя и пароль, а значит, воспользоваться защищённым протоколом наподобие HTTPS (вместо HTTP) или FTPS (вместо FTP). Если по каким-то причинам приходится использовать протокол без шифрования, то убедитесь, что вы используете способ аутентификации, не передающий учётные данные в виде простого текста (например, аутентификацию Digest, NTLM или Negotiate).
Также curl поддерживает использование файлов конфигурации .curlrc, _curlrc и .netrc, позволяющих задавать различные опции curl в файле, а затем добавлять файл в команду при помощи опции curl —config (или curl -K), что особенно полезно при написании скриптов.
▍ Выгрузка файла
Опция —upload-file (или -T) позволяет выгружать локальный файл на удалённый сервер. Показанная ниже команда выгружает файл из локальной системы на удалённый веб-сервер по протоколу FTPS:
curl -kT C:UsersSurenderDownloadssample1.zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка файла на удалённый сервер
Опция -k добавляется для устранения проблем с сертификатами на случай, если веб-сервер использует самоподписанный сертификат. Наклонная черта в конце URL сообщает curl, что конечная точка является папкой. Можно указать несколько имён файлов, например «{sample1.zip,sample2.zip}». Ниже показано, как с помощью одной команды curl можно выгрузить на сервер несколько файлов:
curl -kT sample[1-5].zip -u testlabsurender ftps://192.168.0.80/awesomewebsite.com/files/
Выгрузка нескольких файлов на сервер
▍ Последовательность команд
Как говорилось ранее, curl поддерживает различные методы в зависимости от используемого протокола. Дополнительные команды можно отправлять при помощи —quote (или -Q) для выполнения операции до или после обычной операции curl. Например, можно скачать файл с удалённого сервера по протоколу FTPS и удалить файл с сервера после успешного скачивания. Для этого нужно выполнить следующую команду:
curl -u testlabsurender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"
Удаление файла после успешного скачивания
В показанном выше примере я скачал файл sample1.zip с FTPS-сервера при помощи опции -O. После опции -Q я добавил минус (-) перед командой DELE, что заставляет curl отправить команду DELE sample1.zip сразу после успешного скачивания файла. Аналогично, если вы хотите отправить команду на сервер до выполнения операции curl, используйте плюс (+) вместо минуса.
▍ Изменение user-agent
Информация user-agent сообщает серверу тип клиента, отправляющего запрос. При отправке запроса curl на сервер по умолчанию используется user-agent curl/<version>. Если сервер настроен так, чтобы блокировать запросы curl, можно задать собственный user-agent при помощи опции —user-agent (или -A). Показанная ниже команда отправляет стандартный user-agent Google Chrome:
curl -kIA "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0" https://awesomewebsite.com/files/secretFile.zip
Использование собственного user-agent с командой curl, чтобы избежать блокировки сервером
На показанном выше скриншоте видно, что обычный запрос curl был отклонён веб-сервером (с ответом 403 Forbidden), но при передаче другого user-agent запрос выполняется успешно, возвращая ответ 200 OK.
▍ Отправка куки
По умолчанию запрос curl не отправляет и не сохраняет куки. Для записи куки можно использовать опцию —cookie-jar (или -c), а отправить куки можно опцией —cookie (or -b):
curl -c /path/cookie_file https://awesomewebsite.com/
curl -b /path/cookie_file https://awesomewebsite.com/
Первая команда записывает файл куки, а вторая отправляет куки с запросом curl. Также можно отправить куки в формате ‘name = value’:
curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io
Отправка нескольких куки командой curl
Я воспользовался веб-сайтом echo.hoppscotch.io для демонстрации заголовков HTTP-запросов, которые обычно невидимы клиентам, отправляющим запрос. Если вы не хотите пользоваться этим веб-сайтом, то можете применить опцию –verbose (или -v) для отображения запроса в сыром виде (который отображает и заголовки запросов).
▍ Использование прокси-сервера
Если вы пользуетесь прокси-сервером для подключения к интернету, в curl можно указать прокси опцией —proxy (или -x). Если прокси-сервер требует аутентификации, то добавьте —proxy-user (или -U):
curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/
Прокси-сервер указывается в формате server:port, а пользователь прокси — в формате username:password. Можно не вводить пароль пользователя прокси, тогда curl попросит ввести его в режиме no-echo.
Использование прокси-сервера и аутентификации
▍ Дополнительные заголовки запросов
Иногда вместе с запросом к серверу необходимо отправить дополнительную информацию. В curl это можно сделать при помощи —header (или -H), как показано в следующей команде:
curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com
Указание дополнительных заголовков для запроса curl
Можно отправлять любую информацию, недоступную через стандартные заголовки HTTP-запросов. В этом примере я отправил название своей операционной системы. Также я добавил опцию -v для включения verbose-вывода, отображающего дополнительный заголовок, отправляемый вместе с каждым моим запросом curl.
▍ Отправка электронного письма
Так как curl поддерживает протокол SMTP, его можно использовать для отправки электронного письма. Показанная ниже команда позволяет отправить электронное письмо при помощи curl:
curl --insecure --ssl-reqd smtps://mail.yourdomain.com –-mail-from sender@yourdomain.com –-mail-rcpt receiver@company.com --user sender@yourdomain.com --upload-file email_msg.txt
Отправка электронного письма командой curl
Давайте вкратце перечислим использованные здесь опции:
- Опция —insecure (или -k) используется, чтобы избежать ошибки сертификата SSL. Мы уже применяли её ранее.
- Опция —ssl-reql используется для апгрейда соединения передачи простого текста до зашифрованного соединения, если оно поддерживается SMTP-сервером. Если вы уверены, что ваш SMTP-сервер поддерживает SSL, то можно использовать непосредственно имя сервера smtps (например, smtps://smtp.yourdomain.com), как показано на скриншоте.
- Опция —mail-from используется для указания адреса электронной почты отправителя.
- Опция mail-rcpt указывает адрес электронной почты получателя.
- Опция —user (или -u) отправляет имя пользователя для аутентификации, оно должно совпадать с адресом mail-from, потому что в противном случае письмо может быть отклонено или помечено как спам.
- Опция —upload-file (или -T) используется для указания файла, в котором находится отправляемое письмо.
На скриншоте ниже показано письмо, полученное мной во входящие:
Просмотр письма, отправленного с помощью curl
Это всего лишь несколько примеров использования curl — на самом деле их гораздо больше. Я настоятельно рекомендую проверить справку по curl и поэкспериментировать с ней.
А вы используете curl? И если да, то для чего?
Telegram-канал с полезностями и уютный чат