How to install curl on windows

I am having trouble getting cURL to run on Windows. I have downloaded a cURL zip file from here, but it seems to contain source code, not an executable. Do I need to compile cURL to run it? If yes,...

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.

how to install curl and libcurl

Installing Binary Packages

Lots of people download binary distributions of curl and libcurl. This
document does not describe how to install curl or libcurl using such a binary
package. This document describes how to compile, build and install curl and
libcurl from source code.

Building using vcpkg

You can download and install curl and libcurl using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install curl[tool]

The curl port in vcpkg is kept up to date by Microsoft team members and
community contributors. If the version is out of date, please create an issue
or pull request on the vcpkg repository.

Building from git

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

Unix

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

./configure --with-openssl [--with-gnutls --with-wolfssl]
make
make test (optional)
make install

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

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

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

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

./configure --prefix=/path/to/curl/tree

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

./configure --prefix=$HOME
make
make install

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

./configure --with-openssl

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

env PKG_CONFIG_PATH=/opt/OpenSSL/lib/pkgconfig ./configure --with-openssl

Without pkg-config installed, use this:

./configure --with-openssl=/opt/OpenSSL

If you insist on forcing a build without SSL support, you can run configure
like this:

./configure --without-ssl

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

CPPFLAGS="-I/path/to/ssl/include" LDFLAGS="-L/path/to/ssl/lib" ./configure

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

LDFLAGS=-Wl,-R/usr/local/ssl/lib ./configure --with-openssl

Static builds

To force a static library compile, disable the shared library creation by
running configure like:

./configure --disable-shared

The configure script is primarily done to work with shared/dynamic third party
dependencies. When linking with shared libraries, the dependency «chain» is
handled automatically by the library loader — on all modern systems.

If you instead link with a static library, you need to provide all the
dependency libraries already at the link command line.

Figuring out all the dependency libraries for a given library is hard, as it
might involve figuring out the dependencies of the dependencies and they vary
between platforms and change between versions.

When using static dependencies, the build scripts will mostly assume that you,
the user, will provide all the necessary additional dependency libraries as
additional arguments in the build. With configure, by setting LIBS or
LDFLAGS on the command line.

Building statically is not for the faint of heart.

Debug

If you are a curl developer and use gcc, you might want to enable more debug
options with the --enable-debug option.

curl can be built to use a whole range of libraries to provide various useful
services, and configure will try to auto-detect a decent default. But if you
want to alter it, you can select how to deal with each individual library.

Select TLS backend

These options are provided to select the TLS backend to use.

  • AmiSSL: --with-amissl
  • BearSSL: --with-bearssl
  • GnuTLS: --with-gnutls.
  • mbedTLS: --with-mbedtls
  • NSS: --with-nss
  • OpenSSL: --with-openssl (also for BoringSSL, libressl and quictls)
  • rustls: --with-rustls
  • Schannel: --with-schannel
  • Secure Transport: --with-secure-transport
  • wolfSSL: --with-wolfssl

You can build curl with multiple TLS backends at your choice, but some TLS
backends cannot be combined: if you build with an OpenSSL fork (or wolfSSL),
you cannot add another OpenSSL fork (or wolfSSL) simply because they have
conflicting identical symbol names.

When you build with multiple TLS backends, you can select the active one at
run-time when curl starts up.

Windows

Building Windows DLLs and C runtime (CRT) linkage issues

As a general rule, building a DLL with static CRT linkage is highly
discouraged, and intermixing CRTs in the same app is something to avoid at
any cost.

Reading and comprehending Microsoft Knowledge Base articles KB94248 and
KB140584 is a must for any Windows developer. Especially important is full
understanding if you are not going to follow the advice given above.

  • How To Use the C Run-Time
  • Run-Time Library Compiler Options
  • Potential Errors Passing CRT Objects Across DLL Boundaries

If your app is misbehaving in some strange way, or it is suffering from memory
corruption, before asking for further help, please try first to rebuild every
single library your app uses as well as your app using the debug
multi-threaded dynamic C runtime.

If you get linkage errors read section 5.7 of the FAQ document.

MinGW32

Make sure that MinGW32’s bin directory is in the search path, for example:

set PATH=c:mingw32bin;%PATH%

then run mingw32-make mingw32 in the root dir. There are other
make targets available to build libcurl with more features, use:

  • mingw32-make mingw32-zlib to build with Zlib support;
  • mingw32-make mingw32-ssl-zlib to build with SSL and Zlib enabled;
  • mingw32-make mingw32-ssh2-ssl-zlib to build with SSH2, SSL, Zlib;
  • mingw32-make mingw32-ssh2-ssl-sspi-zlib to build with SSH2, SSL, Zlib
    and SSPI support.

If you have any problems linking libraries or finding header files, be sure
to verify that the provided Makefile.mk files use the proper paths, and
adjust as necessary. It is also possible to override these paths with
environment variables, for example:

set ZLIB_PATH=c:zlib-1.2.12
set OPENSSL_PATH=c:openssl-3.0.5
set LIBSSH2_PATH=c:libssh2-1.10.0

It is also possible to build with other LDAP installations than MS LDAP;
currently it is possible to build with native Win32 OpenLDAP, or with the
Novell CLDAP SDK. If you want to use these you need to set these vars:

set CPPFLAGS=-Ic:/openldap/include -DCURL_HAS_OPENLDAP_LDAPSDK
set LDFLAGS=-Lc:/openldap/lib
set LIBS=-lldap -llber

or for using the Novell SDK:

set CPPFLAGS=-Ic:/openldapsdk/inc -DCURL_HAS_NOVELL_LDAPSDK
set LDFLAGS=-Lc:/openldapsdk/lib/mscvc
set LIBS=-lldapsdk -lldapssl -lldapx

If you want to enable LDAPS support then append -ldaps to the make target.

Cygwin

Almost identical to the Unix installation. Run the configure script in the
curl source tree root with sh configure. Make sure you have the sh
executable in /bin/ or you will see the configure fail toward the end.

Run make

MS-DOS

Requires DJGPP in the search path and pointing to the Watt-32 stack via
WATT_PATH=c:/djgpp/net/watt.

Run make -f Makefile.dist djgpp in the root curl dir.

For build configuration options, please see the MinGW32 section.

Notes:

  • DJGPP 2.04 beta has a sscanf() bug so the URL parsing is not done
    properly. Use DJGPP 2.03 until they fix it.

  • Compile Watt-32 (and OpenSSL) with the same version of DJGPP. Otherwise
    things go wrong because things like FS-extensions and errno values have
    been changed between releases.

AmigaOS

Run make -f Makefile.dist amiga in the root curl dir.

For build configuration options, please see the MinGW32 section.

Disabling Specific Protocols in Windows builds

The configure utility, unfortunately, is not available for the Windows
environment, therefore, you cannot use the various disable-protocol options of
the configure utility on this platform.

You can use specific defines to disable specific protocols and features. See
CURL-DISABLE for the full list.

If you want to set any of these defines you have the following options:

  • Modify lib/config-win32.h
  • Modify lib/curl_setup.h
  • Modify winbuild/Makefile.vc
  • Modify the «Preprocessor Definitions» in the libcurl project

Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Properties -> Configuration Properties -> C/C++ ->
Preprocessor».

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

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

  • Modify lib/config-win32.h and src/config-win32.h
  • Modify winbuild/Makefile.vc
  • Modify the «Preprocessor Definitions» in the libcurl project

Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Properties -> Configuration Properties -> C/C++ ->
Preprocessor».

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

Compilation has been verified with lwIP 1.4.0.

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

Important static libcurl usage note

When building an application that uses the static libcurl library on Windows,
you must add -DCURL_STATICLIB to your CFLAGS. Otherwise the linker will
look for dynamic import symbols.

Legacy Windows and SSL

Schannel (from Windows SSPI), is the native SSL library in Windows. However,
Schannel in Windows <= XP is unable to connect to servers that
no longer support the legacy handshakes and algorithms used by those
versions. If you will be using curl in one of those earlier versions of
Windows you should choose another SSL backend such as OpenSSL.

Apple Platforms (macOS, iOS, tvOS, watchOS, and their simulator counterparts)

On modern Apple operating systems, curl can be built to use Apple’s SSL/TLS
implementation, Secure Transport, instead of OpenSSL. To build with Secure
Transport for SSL/TLS, use the configure option --with-secure-transport.

When Secure Transport is in use, the curl options --cacert and --capath
and their libcurl equivalents, will be ignored, because Secure Transport uses
the certificates stored in the Keychain to evaluate whether or not to trust
the server. This, of course, includes the root certificates that ship with the
OS. The --cert and --engine options, and their libcurl equivalents, are
currently unimplemented in curl with Secure Transport.

In general, a curl build for an Apple ARCH/SDK/DEPLOYMENT_TARGET combination
can be taken by providing appropriate values for ARCH, SDK, DEPLOYMENT_TARGET
below and running the commands:

# Set these three according to your needs
export ARCH=x86_64
export SDK=macosx
export DEPLOYMENT_TARGET=10.8

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

Above will build curl for macOS platform with x86_64 architecture and 10.8 as deployment target.

Here is an example for iOS device:

export ARCH=arm64
export SDK=iphoneos
export DEPLOYMENT_TARGET=11.0

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

Another example for watchOS simulator for macs with Apple Silicon:

export ARCH=arm64
export SDK=watchsimulator
export DEPLOYMENT_TARGET=5.0

export CFLAGS="-arch $ARCH -isysroot $(xcrun -sdk $SDK --show-sdk-path) -m$SDK-version-min=$DEPLOYMENT_TARGET"
./configure --host=$ARCH-apple-darwin --prefix $(pwd)/artifacts --with-secure-transport
make -j8
make install

In all above, the built libraries and executables can be found in the
artifacts folder.

Android

When building curl for Android it’s recommended to use a Linux/macOS environment
since using curl’s configure script is the easiest way to build curl
for Android. Before you can build curl for Android, you need to install the
Android NDK first. This can be done using the SDK Manager that is part of
Android Studio. Once you have installed the Android NDK, you need to figure out
where it has been installed and then set up some environment variables before
launching configure. On macOS, those variables could look like this to compile
for aarch64 and API level 29:

export ANDROID_NDK_HOME=~/Library/Android/sdk/ndk/25.1.8937393 # Point into your NDK.
export HOST_TAG=darwin-x86_64 # Same tag for Apple Silicon. Other OS values here: https://developer.android.com/ndk/guides/other_build_systems#overview
export TOOLCHAIN=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$HOST_TAG
export AR=$TOOLCHAIN/bin/llvm-ar
export AS=$TOOLCHAIN/bin/llvm-as
export CC=$TOOLCHAIN/bin/aarch64-linux-android21-clang
export CXX=$TOOLCHAIN/bin/aarch64-linux-android21-clang++
export LD=$TOOLCHAIN/bin/ld
export RANLIB=$TOOLCHAIN/bin/llvm-ranlib
export STRIP=$TOOLCHAIN/bin/llvm-strip

When building on Linux or targeting other API levels or architectures, you need
to adjust those variables accordingly. After that you can build curl like this:

./configure --host aarch64-linux-android --with-pic --disable-shared

Note that this will not give you SSL/TLS support. If you need SSL/TLS, you have
to build curl against a SSL/TLS layer, e.g. OpenSSL, because it’s impossible for
curl to access Android’s native SSL/TLS layer. To build curl for Android using
OpenSSL, follow the OpenSSL build instructions and then install libssl.a and
libcrypto.a to $TOOLCHAIN/sysroot/usr/lib and copy include/openssl to
$TOOLCHAIN/sysroot/usr/include. Now you can build curl for Android using
OpenSSL like this:

LIBS="-lssl -lcrypto -lc++" # For OpenSSL/BoringSSL. In general, you'll need to the SSL/TLS layer's transtive dependencies if you're linking statically.
./configure --host aarch64-linux-android --with-pic --disable-shared --with-openssl="$TOOLCHAIN/sysroot/usr"

IBM i

For IBM i (formerly OS/400), you can use curl in two different ways:

  • Natively, running in the ILE. The obvious use is being able to call curl
    from ILE C or RPG applications.

    • You will need to build this from source. See packages/OS400/README for
      the ILE specific build instructions.
  • In the PASE environment, which runs AIX programs. curl will be built as
    it would be on AIX.

    • IBM provides builds of curl in their Yum repository for PASE software.
    • To build from source, follow the Unix instructions.

There are some additional limitations and quirks with curl on this platform;
they affect both environments.

Multi-threading notes

By default, jobs in IBM i will not start with threading enabled. (Exceptions
include interactive PASE sessions started by QP2TERM or SSH.) If you use
curl in an environment without threading when options like asynchronous DNS
were enabled, you will get messages like:

getaddrinfo() thread failed to start

Do not panic. curl and your program are not broken. You can fix this by:

  • Set the environment variable QIBM_MULTI_THREADED to Y before starting
    your program. This can be done at whatever scope you feel is appropriate.
  • Alternatively, start the job with the ALWMLTTHD parameter set to *YES.

Cross compile

Download and unpack the curl package.

cd to the new directory. (e.g. cd curl-7.12.3)

Set environment variables to point to the cross-compile toolchain and call
configure with any options you need. Be sure and specify the --host and
--build parameters at configuration time. The following script is an example
of cross-compiling for the IBM 405GP PowerPC processor using the toolchain on
Linux.

#! /bin/sh

export PATH=$PATH:/opt/hardhat/devkit/ppc/405/bin
export CPPFLAGS="-I/opt/hardhat/devkit/ppc/405/target/usr/include"
export AR=ppc_405-ar
export AS=ppc_405-as
export LD=ppc_405-ld
export RANLIB=ppc_405-ranlib
export CC=ppc_405-gcc
export NM=ppc_405-nm

./configure --target=powerpc-hardhat-linux
    --host=powerpc-hardhat-linux
    --build=i586-pc-linux-gnu
    --prefix=/opt/hardhat/devkit/ppc/405/target/usr/local
    --exec-prefix=/usr/local

You may also need to provide a parameter like --with-random=/dev/urandom to
configure as it cannot detect the presence of a random number generating
device for a target system. The --prefix parameter specifies where curl
will be installed. If configure completes successfully, do make and make install as usual.

In some cases, you may be able to simplify the above commands to as little as:

./configure --host=ARCH-OS

REDUCING SIZE

There are a number of configure options that can be used to reduce the size of
libcurl for embedded applications where binary size is an important factor.
First, be sure to set the CFLAGS variable when configuring with any relevant
compiler optimization flags to reduce the size of the binary. For gcc, this
would mean at minimum the -Os option, and potentially the -march=X,
-mdynamic-no-pic and -flto options as well, e.g.

./configure CFLAGS='-Os' LDFLAGS='-Wl,-Bsymbolic'...

Note that newer compilers often produce smaller code than older versions
due to improved optimization.

Be sure to specify as many --disable- and --without- flags on the
configure command-line as you can to disable all the libcurl features that you
know your application is not going to need. Besides specifying the
--disable-PROTOCOL flags for all the types of URLs your application will not
use, here are some other flags that can reduce the size of the library by
disabling support for some feature:

  • --disable-alt-svc (HTTP Alt-Svc)
  • --disable-ares (the C-ARES DNS library)
  • --disable-cookies (HTTP cookies)
  • --disable-crypto-auth (cryptographic authentication)
  • --disable-dateparse (date parsing for time conditionals)
  • --disable-dnsshuffle (internal server load spreading)
  • --disable-doh (DNS-over-HTTP)
  • --disable-get-easy-options (lookup easy options at runtime)
  • --disable-hsts (HTTP Strict Transport Security)
  • --disable-http-auth (all HTTP authentication)
  • --disable-ipv6 (IPv6)
  • --disable-libcurl-option (—libcurl C code generation support)
  • --disable-manual (built-in documentation)
  • --disable-netrc (.netrc file)
  • --disable-ntlm-wb (NTLM WinBind)
  • --disable-progress-meter (graphical progress meter in library)
  • --disable-proxy (HTTP and SOCKS proxies)
  • --disable-pthreads (multi-threading)
  • --disable-socketpair (socketpair for asynchronous name resolving)
  • --disable-threaded-resolver (threaded name resolver)
  • --disable-tls-srp (Secure Remote Password authentication for TLS)
  • --disable-unix-sockets (UNIX sockets)
  • --disable-verbose (eliminates debugging strings and error code strings)
  • --disable-versioned-symbols (versioned symbols)
  • --enable-symbol-hiding (eliminates unneeded symbols in the shared library)
  • --without-brotli (Brotli on-the-fly decompression)
  • --without-libpsl (Public Suffix List in cookies)
  • --without-nghttp2 (HTTP/2 using nghttp2)
  • --without-ngtcp2 (HTTP/2 using ngtcp2)
  • --without-zstd (Zstd on-the-fly decompression)
  • --without-libidn2 (internationalized domain names)
  • --without-librtmp (RTMP)
  • --without-ssl (SSL/TLS)
  • --without-zlib (on-the-fly decompression)

The GNU compiler and linker have a number of options that can reduce the
size of the libcurl dynamic libraries on some platforms even further.
Specify them by providing appropriate CFLAGS and LDFLAGS variables on
the configure command-line, e.g.

CFLAGS="-Os -ffunction-sections -fdata-sections
        -fno-unwind-tables -fno-asynchronous-unwind-tables -flto"
LDFLAGS="-Wl,-s -Wl,-Bsymbolic -Wl,--gc-sections"

Be sure also to strip debugging symbols from your binaries after compiling
using ‘strip’ (or the appropriate variant if cross-compiling). If space is
really tight, you may be able to remove some unneeded sections of the shared
library using the -R option to objcopy (e.g. the .comment section).

Using these techniques it is possible to create a basic HTTP-only libcurl
shared library for i386 Linux platforms that is only 133 KiB in size
(as of libcurl version 7.80.0, using gcc 11.2.0).

You may find that statically linking libcurl to your application will result
in a lower total size than dynamically linking.

Note that the curl test harness can detect the use of some, but not all, of
the --disable statements suggested above. Use will cause tests relying on
those features to fail. The test harness can be manually forced to skip the
relevant tests by specifying certain key words on the runtests.pl command
line. Following is a list of appropriate key words for those configure options
that are not automatically detected:

  • --disable-cookies !cookies
  • --disable-dateparse !RETRY-AFTER !CURLOPT_TIMECONDITION !CURLINFO_FILETIME !If-Modified-Since !curl_getdate !-z
  • --disable-libcurl-option !--libcurl
  • --disable-verbose !verbose logs

PORTS

This is a probably incomplete list of known CPU architectures and operating
systems that curl has been compiled for. If you know a system curl compiles
and runs on, that is not listed, please let us know!

92 Operating Systems

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

26 CPU Architectures

Alpha, ARC, ARM, AVR32, CompactRISC, Elbrus, ETRAX, HP-PA, Itanium,
LoongArch, m68k, m88k, MicroBlaze, MIPS, Nios, OpenRISC, POWER, PowerPC,
RISC-V, s390, SH4, SPARC, Tilera, VAX, x86, Xtensa

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

Silently download a file and save with a custom name using curl

Скачивание файла без индикатора и сохранение под произвольным именем

▍ Продолжение прерванного скачивания

Наличие 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

  1. Install curl on Windows
  2. Curl syntax
  3. HTTP GET request
  4. Get remote file information.
  5. Download a file
  6. Resume interrupted download
  7. Authentication with Curl
  8. Upload a file
  9. Quote a command
  10. Change the user-agent
  11. Send a cookie
  12. Use a proxy server
  13. Additional request headers
  14. 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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:

curl download screenshot

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

  1. Post Variables
  2. Post a file
  3. 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.


Download Article

An easy-to-follow guide on how to install cURL on your computer


Download Article

cURL is short for Client URL and is a command-line or script used to transfer data.[1]
This wikiHow will show you how to install cURL on Windows.

Steps

  1. Image titled Install Curl on Windows Step 1

    1

    Go to https://curl.haxx.se/download.html in a web browser. cURL is used in command lines or scripts to transfer data. For example curl https://www.wikihow.com will return the HTTP response.

  2. Image titled Install Curl on Windows Step 2

    2

    Click curl Download Wizard. You’ll see this under the «Download Wizard» header.

    Advertisement

  3. Image titled Install Curl on Windows Step 3

    3

    Click curl executable. This is usually the first listing in the menu.

  4. Image titled Install Curl on Windows Step 4

    4

    Click the drop-down under «Select Operating System» and select Windows 32 or 64. If your CPU is a 32-bit processor, you’ll need to download the 32-bit version; if your CPU is a 64-bit processor, you can download either, but the 64-bit version of cURL will take full advantage of your CPU’s benefits.[2]

  5. Image titled Install Curl on Windows Step 5

    5

    Click Select. This is next to the drop-down menu of available OS-compatible downloads.

  6. Image titled Install Curl on Windows Step 6

    6

    Select what version you want (only available for certain downloads, like Win32). Some builds of cURL, like with Win32, have different versions. Click the drop-down to select a version.

    • If «Generic» is available, choose that.
    • Click Select to continue. You’ll be directed to a page of recommended downloads.
  7. Image titled Install Curl on Windows Step 7

    7

    Click the arrow in the first result. This is usually a link to a download from the official cURL website.

  8. Image titled Install Curl on Windows Step 8

    8

    Click the build you want. You may have to choose between a 32-bit and 64-bit build again.

  9. Image titled Install Curl on Windows Step 9

    9

    Save the downloaded file. When your file browser pops up, choose a location to save the file and click Save.

  10. Image titled Install Curl on Windows Step 10

    10

    Extract the files from the zipped folder. A zipped file will download to the location you specified, and you’ll need to unzip the folder to continue.

    • Right-click on the folder and select ‘Extract All, then specify a location where you want to unzip the files to.
  11. Image titled Install Curl on Windows Step 11

    11

    Open the unzipped folder and files and find «curl.exe.«. You’ll find the root folder in the location you previously specified. And you’ll probably find «curl.exe» in the bin folder.

  12. Image titled Install Curl on Windows Step 12

    12

    Type «cmd» in the address bar of your file browser to launch a command window. You can also type «CMD» in the search area of the Start Menu.

  13. Image titled Install Curl on Windows Step 13

    13

    Type «curl» into the command window and press Enter. If you opened the command window from the address bar of file browser while you were navigated in the «bin» folder, command prompt should already have the appropriate address entered.

    • You should see command prompt return to you commands that you can try with curl.[3]
    • You can use the curl command on your computer from that specific path. If you type «curl» in command prompt at a path different from where it’s located (in the «bin» folder of the unzipped folder), it will not work.
  14. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

References

About This Article

Article SummaryX

1. Go to https://curl.haxx.se/download.html in a web browser.

2. Click curl Download Wizard.

3. Click curl executable.
4. Click the drop-down under «Select Operating System» and select Windows 32 or 64.

5. Click Select.

6. Select what version you want (only available for certain downloads, like Win32).

7. Click the arrow in the first result.

8. Click the build you want.

9. Save the downloaded file.

10. Extract the files from the zipped folder.

11. Open the unzipped folder and files and find «curl.exe.»

12. Type «cmd» in the address bar of your file browser to launch a command window.

13. Type «curl» into the command window and press Enter.

Did this summary help you?

Thanks to all authors for creating a page that has been read 25,907 times.

Is this article up to date?

Как установить CURL на Windows 10

cURL — кроссплатформенная служебная программа командной строки, позволяющая взаимодействовать с множеством различных серверов по множеству различных протоколов с синтаксисом URL. Она бесплатна и используется многими приложениями. В этой заметке я расскажу о том, как устанавливать CURL на Windows.

Начиная с Windows 10 v1803, операционная система уже поставляется с копией CURL. Она уже настроена и вы можете приступать к ее использованию прямо сейчас. Откройте командную строку и введите «curl -help«. Если ошибок нет, и отображаются все опции CURL, то она установлена на ваш Windows 10.

Как установить CURL на Windows 10 1

Наряду с Curl, Microsoft также запустила Tar, инструмент командной строки для извлечения файлов и создания архивов.

Если по каким-то причинам вы не нашли CURL, установленный на вашей ОС Windows, вот как его установить.

1. Загрузите и установите программу Curl с официального сайта

Перейдите сюда и загрузите версию, которая подходит для вашей системы (32 или 64 bit). Если вы хотите загрузить определенные пакеты, посетите страницу Пакеты CURL. Здесь вы можете скачать исполняемый файл curl, программу разработки libcurl, libcurl или исходный код. Не забудьте добавить исполняемый файл в свой каталог.

2. CURL для Windows

Если вы предпочитаете установщик в 1 щелчок, используйте cURL для Windows. Вы можете скачать его здесь.


Спасибо, что читаете! На данный момент большинство моих заметок, статей и подборок выходит в telegram канале «Левашов». Обязательно подписывайтесь, чтобы не пропустить новости мира ИТ, полезные инструкции и нужные сервисы.


Респект за пост! Спасибо за работу!

Хотите больше постов в блоге? Подборок софта и сервисов, а также обзоры на гаджеты? Сейчас, чтобы писать регулярно и радовать вас большими обзорами, мне требуется помощь. Чтобы поддерживать сайт на регулярной основе, вы можете оформить подписку на российском сервисе Boosty. Или воспользоваться ЮMoney (бывшие Яндекс Деньги) для разовой поддержки:


Заранее спасибо! Все собранные средства будут пущены на развитие сайта. Поддержка проекта является подарком владельцу сайта.

cURL is a command-line tool that lets you transfer data to/from a server using various protocols. In this case, the curl command will establish a communication to POST or GET data to/from Ubidots Server over HTTP and HTTPS.

Below you will find the step-by-step to installing cURL in Windows, MacOSX and Linux.

  1. Windows installation

  2. MacOSX installation

  3. Linux installation

1. Enter and access the URL https://curl.haxx.se/ to download the curl executable wizard.

2. Select «curl executable» as Type of Package.

 3. Then, on the «Select Operating System» section, select Windows. Then, continue selecting the parameters required based on your version of Windows. 

4. Once you’ve finished the on-screen steps, download the zip file generated. To download it, simply press «Download«. 

5. Next, open the .zip file and enter to the folder called «src*». Inside the src folder you will find the curl executable file. At this point, you need to copy the executable file and paste it inside a local folder on your PC to be able to run the curl. 

NOTE: To get a better understanding of the following steps, let’s assume the executable file is located inside a folder named «programs«. 

6. From the Command Prompt, enter to the location where the executable file was pasted. To enter to the folder you need to use the cd command following the location of the folder which contains the executable file as you can see below. 

cd programs

Expected location to be shown

C:Users{your_user}programs>

7. To verify if you are able to run curl commands with the command prompt, test functionality by executing the command below:

curl --help 

At this point, you should receive the all the help info related to the curl command. 

1. Enter to the computer’s terminal. 

2. Run the command below in the terminal:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

3. If a password is required after running the command, please enter your Mac’s user password to continue. Then, wait until the installation finish. 

4. Run the command below in the terminal:

brew install curl

Now you are able to use cURL from your Mac pc!

1. Enter to the computer’s terminal. 

2. Run the command below in the terminal:

sudo apt-get install curl

3. If a password is required after ran the command, please enter your computers’ user password to continue. Then, wait until the installation finishes.

Now you are able to use cURL from your Linux pc!

Понравилась статья? Поделить с друзьями:
  • How to install cudnn on windows
  • How to install cmake on windows
  • How to install chromium on windows
  • How to install chrome on windows 10
  • How to install chocolatey on windows 10