How to Read and Send Cookies with Curl

Using curl to manage cookies is a fundamental skill for web scraping, API testing, and automating web interactions. This article provides a direct, step-by-step guide on how to configure curl to read existing cookies from a local text file, send them with your HTTP requests, and write newly received cookies back to a file.

Reading and Sending Cookies from a File

To make curl read cookies from a local text file and send them to a server, use the -b (or --cookie) option followed by the path to your cookie file.

curl -b cookies.txt https://example.com/profile

In this command, curl parses the cookies.txt file and automatically formats the cookies into the Cookie: HTTP request header.

The cookie file can be in two formats: 1. Netscape Cookie Format: This is the standard tab-delimited format generated by browser extensions (like “GetToken” or “Cookie-Editor”) and curl itself. 2. Key-Value Pairs: A simple text file containing name=value pairs separated by semicolons (e.g., session_id=12345; logged_in=true).

Saving Received Cookies to a File

If you need to perform a login request and save the resulting session cookies to a local file, use the -c (or --cookie-jar) option.

curl -c cookies.txt https://example.com/login

When the server responds with a Set-Cookie header, curl will write those cookies to cookies.txt in the Netscape cookie format.

Reading and Writing Cookies in a Single Command

For stateful browsing sessions where you need to both send existing cookies and save any updated cookies sent back by the server, combine both the -b and -c options using the same file.

curl -b cookies.txt -c cookies.txt https://example.com/dashboard

This ensures that your session remains active and any changes to the session state (such as renewed login tokens) are preserved locally for your next request.