Save cURL Cookies to Local File
This article explains how to use the curl command-line
tool to capture and save HTTP cookies sent by a web server into a local
text file. You will learn the specific command-line options required to
write cookies to a disk, how to read those saved cookies for subsequent
requests, and how to maintain an active session.
Saving Cookies with the Cookie Jar Option
To instruct curl to save received HTTP cookies to a
local file, use the -c (or --cookie-jar)
option followed by the path to the file where you want to store the
cookies.
curl -c cookies.txt https://example.comWhen you run this command, curl connects to the
specified URL, receives the HTTP response, and writes any cookies sent
by the server in the Set-Cookie headers into
cookies.txt using the standard Netscape cookie file format.
If the file does not exist, curl will create it; if it
already exists, curl will overwrite it.
Using Saved Cookies in Subsequent Requests
To send the saved cookies back to the server in a future request, use
the -b (or --cookie) option followed by the
path to the file containing the cookies.
curl -b cookies.txt https://example.com/dashboardThis command reads the cookies from cookies.txt and
includes them in the Cookie request header, allowing you to
authenticate or maintain state with the server.
Combining Reading and Writing for Session Management
For multi-step workflows where you need to both use existing cookies and save new or updated cookies sent by the server, you can combine both options in a single command:
curl -b cookies.txt -c cookies.txt https://example.com/actionIn this command, curl first loads the existing cookies
from cookies.txt to send with the request, and then writes
any updated or new cookies back to cookies.txt once the
transaction is complete.