curl with Cookies and Sessions
Handle cookies in curl with cookie jars, send and receive cookies, and manage sessions across multiple requests. Convert cookie patterns to any language.
Detailed Explanation
Managing Cookies with curl
Cookies are essential for maintaining sessions, tracking authentication state, and storing preferences. curl provides robust cookie handling through cookie jars and header manipulation.
Sending a Cookie
Use -b to send cookies with a request:
curl -b "session_id=abc123; theme=dark" https://example.com/dashboard
Saving Cookies from a Response
Use -c to save received cookies to a file (cookie jar):
curl -c cookies.txt https://example.com/login \
-d "username=admin&password=secret"
Using a Cookie Jar
Combine -b and -c to maintain a persistent session across requests:
# Login and save cookies
curl -c cookies.txt -d "user=admin&pass=secret" https://example.com/login
# Use saved cookies for subsequent requests
curl -b cookies.txt https://example.com/dashboard
curl -b cookies.txt https://example.com/api/data
Cookie Jar File Format
The cookie jar uses Netscape cookie format:
# domain flag path secure expiry name value
.example.com TRUE / TRUE 1735689600 session_id abc123
Session Maintenance
For a full session workflow (login, perform actions, logout):
JAR="session_cookies.txt"
# Login
curl -s -c "$JAR" -X POST https://example.com/login \
-d '{"email":"user@example.com","password":"pass"}' \
-H "Content-Type: application/json"
# Authenticated request
curl -s -b "$JAR" -c "$JAR" https://example.com/api/profile
# Logout
curl -s -b "$JAR" -X POST https://example.com/logout
# Clean up
rm "$JAR"
Cookie Security Headers
Modern cookies include security attributes that curl respects:
- Secure: Only sent over HTTPS
- HttpOnly: Cannot be accessed by JavaScript (irrelevant for curl)
- SameSite: Controls cross-origin behavior
Important Notes
- Use
-bwith a filename to read from a cookie jar file, or with a string to send inline cookies - The
-cflag creates or overwrites the cookie file on each request - Use both
-band-cpointing to the same file to accumulate cookies across multiple requests
Use Case
A QA engineer needs to test an authenticated web application workflow by logging in, performing actions across multiple pages, and verifying session persistence.