Cookies maintain client-specific state and preferences, allowing websites to tailor experiences and provide persistent sessions. While browsers manage cookies automatically, cURL requires manual involvement to include or load cookies. Adding cookies to requests helps simulate browser-like behavior when scraping, testing, or interacting with services expecting stateful requests.

By passing cookies explicitly, you can replicate authenticated sessions or preserve user-specific settings between multiple HTTP calls. This is useful in automation, web scraping, or API testing scenarios where maintaining continuity across requests is required.

Using --cookie, you can send manually set cookies or load them from a saved file. Controlling cookie behavior in cURL grants flexible and reliable testing of scenarios that rely on session state, without needing a full browser.

Steps to add cookies to cURL requests:

  1. Open a terminal.
  2. Make a basic request without cookies.
    $ curl "https://www.example.com/"
  3. Add a cookie directly with --cookie.
    $ curl --cookie "name=value" "http://www.example.com/" --verbose
    > Cookie: name=value

    Use --cookie to send a specific cookie name-value pair.

  4. Include multiple cookies separated by semicolons.
    $ curl --cookie "name1=value1; name2=value2" "http://www.example.com/" --verbose
    > Cookie: name1=value1; name2=value2

    Add as many cookies as needed, separated by semicolons.

  5. Load cookies from a previously saved cookie file.
    $ curl --cookie "/path/to/cookie-file.txt" "https://www.example.com/"

    cURL supports cookie files in Netscape/Mozilla formats. Using --cookie with a file simulates a stored session.

Discuss the article:

Comment anonymously. Login not required.