Does curl Automatically Manage Cookies
This article explains how the curl command-line tool
handles HTTP cookies during network requests. You will learn whether
curl manages cookies automatically by default, how its
cookie engine behaves, and the specific flags required to save, load,
and maintain cookie sessions across multiple requests.
By default, curl does not automatically
manage, store, or send cookies. If a server responds with a
Set-Cookie header, curl will discard the
cookie immediately after the request completes. To persist cookies
across multiple requests or sessions, you must explicitly enable
curl’s cookie engine using specific command-line flags.
To manage cookies effectively, curl relies on two
primary flags: -b (or --cookie) to read/send
cookies, and -c (or --cookie-jar) to
write/save cookies.
Saving Cookies to a File
To capture cookies sent by a server and save them to a file, use the
-c (or --cookie-jar) flag followed by a file
path. This tells curl to write all received cookies to that
file in the Netscape cookie format once the transfer is complete.
curl -c cookies.txt https://example.com/loginSending Cookies from a File
To send previously saved cookies back to a server in a subsequent
request, use the -b (or --cookie) flag
followed by the path to your cookie file.
curl -b cookies.txt https://example.com/dashboardYou can also use the -b flag to pass raw cookie strings
directly without utilizing a file:
curl -b "session_id=123456; user=john" https://example.com/dashboardMaintaining a Session (Combining Flags)
For complex workflows, such as logging into a website and then
accessing a protected page, you should combine both flags. This allows
curl to read existing cookies and write any new or updated
cookies back to the same file.
curl -b cookies.txt -c cookies.txt https://example.com/profileEnabling Temporary In-Memory Cookies
If you only need to handle cookies during a single command
execution—such as following redirects (-L) that set and
immediately require a cookie—you do not need to write them to a physical
disk. You can activate curl’s internal, temporary cookie
engine by passing an empty string to the -b flag:
curl -L -b "" https://example.comUsing -b "" activates the cookie parser, allowing
curl to accept and re-send cookies for the duration of that
single command run, discarding them entirely once the process exits.