Cookies are small data sets stored on a user's device, used for communication between the client and server. They often contain session information, user preferences, and authentication tokens. These cookies enable a website to recognize users, maintain sessions, and deliver personalized content.

cURL, by default, does not handle cookies unless explicitly specified. When working with web applications that require session tracking or authentication, it is often necessary to send cookies in the request. cURL allows users to include cookies in their HTTP requests for more accurate testing, automation, or web scraping.

You can manually set cookies in cURL requests or load them from a saved file. cURL also supports sending multiple cookies and reading cookies from browser-compatible cookie files. This allows for flexible interactions with websites that rely on cookies for stateful sessions and user-specific data.

Steps to add cookies to cURL requests:

  1. Open the terminal.
  2. Run a cURL request to your target URL.
    $ curl https://www.example.com/
  3. Add a cookie to the request using the -b or --cookie parameter.
    $ 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. Separate the cookie's name and value using 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.

  4. Add multiple cookies by using a semicolon as the separator.
    $ 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  

    To include multiple cookies in a single request, use a semicolon (;) as a delimiter between cookies.

  5. Use a saved cookie file by specifying the path to the file.
    $ curl -b "/path/to/cookie-file.txt" https://www.example.com/

    cURL supports cookie files from Netscape, Mozilla, and Lynx formats. Use the -b or --cookie parameter to specify the file path.

Discuss the article:

Comment anonymously. Login not required.