Cookies maintain session state and user preferences across HTTP requests. While browsers handle cookies automatically, cURL requires explicit instructions to save them. Storing cookies allows maintaining logged-in states or session continuity across multiple requests.
By using --cookie-jar, cURL writes server-set cookies to a file. Subsequent requests can load these cookies with --cookie, ensuring the server recognizes the ongoing session. This supports automation and testing scenarios that rely on consistent state.
Careful cookie file management controls their lifecycle and security. This approach reduces repetitive logins and streamlines complex workflows, improving efficiency and reliability when interacting with stateful applications.
Steps to save cookies from cURL request:
- Open a terminal.
- Send a request and use --cookie-jar to save cookies.
$ curl --cookie-jar cookies.txt "https://www.example.com"
Cookies set by the server are written to cookies.txt.
- Inspect the saved cookie file.
$ cat cookies.txt # Netscape HTTP Cookie File ...
The file uses the Netscape format for compatibility.
- Load saved cookies into subsequent requests using --cookie.
$ curl --cookie cookies.txt "https://www.example.com/profile"
Loading cookies maintains session continuity.
- Reuse and update cookies with both --cookie and --cookie-jar.
$ curl --cookie cookies.txt --cookie-jar cookies.txt "https://www.example.com/update-profile"
This approach perpetuates an active session over multiple interactions.
- Remove the cookie file if it contains sensitive data.
$ rm cookies.txt
Protect session cookies to prevent unauthorized access.
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.