Cookies are small data stored on a user's computer by a web browser. They are used in HTTP requests to send information from the client to the server and back. Cookies store user session information, such as preferences, shopping cart contents, or authentication status. Cookies are also used to track users across different websites and to serve targeted ads.
cURL does not use cookies by default, though it's sometimes necessary to include them in your requests to interact with web applications that require them. They can be used to simulate browser sessions for testing your web application, automate web requests to observe specific behaviors, or conduct in-depth vulnerability assessments to pinpoint potential security threats.
There are multiple methods for incorporating cookies with cURL. You can specify them as parameters in your requests or reference cookies pre-crafted and stored in a file. You can use a single cookie or multiple cookies simultaneously in your requests.
Steps to add a cookie to a cURL request:
- Open the terminal.
- Execute a cURL request for your target URL.
$ curl https://www.example.com/
- Manually set the cookie's name and value using the -b or --cookie.
$ curl -b "name=value" http://www.example.com/ -v 2>&1 | grep '^>' > GET / HTTP/1.1 > Host: www.example.com > User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0 > Accept: */* > Cookie: name=value >
Use the -b or --cookie parameter to set the cookie's name and value. The cookie's name and value must be separated by an equal (=) sign.
Use the -v or --verbose parameter to display detailed information about the request and the server's response, and 2>&1 | grep '^>' parameter to filter the output. These are for demonstration purposes only and are not required for normal cURL requests.
- Use a semicolon as the separator to use multiple cookies.
$ curl -b "name1=value1; name2=value2" http://www.example.com/ -v 2>&1 | grep '^>' > Host: www.example.com > User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0 > Accept: */* > Cookie: name1=value1; name2=value2 >
- Use a saved cookie file to add cookies to cURL requests.
$ curl -b "/path/to/cookie-file.txt" https://www.example.com/
cURL support the use of Netscape, Mozilla, and Lynx cookie files.
Use the -b or --cookie parameter to specify the path to the cookie file.
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.