How to use cookies with curl

Posted . Visible to the public.

When making requests using curl, no cookies are sent or stored by default.
However, you can tell curl to re-use cookies received earlier (or forge your own cookies).

There are 2 command line switches you need to use:

  • -c will write cookies to a given file
  • -b will read cookies from a given file

Example

The remote server sets a "foo" cookie to value "bar". We tell curl to store them to a file at /tmp/cookies using the -c switch.

$ curl -c /tmp/cookies http://httpbin.org/cookies/set?foo=bar

You may look at the file, or even modify it, as it's human-readable:

$ cat /tmp/cookies
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

httpbin.org	FALSE	/	FALSE	0	foo	bar

To send cookies to a server, use the -b switch. This URL will render any cookies it received:

$ curl -b /tmp/cookies http://httpbin.org/cookies
{
  "cookies": {
    "foo": "bar"
  }
}

If you want to both send and store cookies, you need to supply both switches.

You can optionally use the -j switch to tell curl to discard any cookies with "Session" expiry.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2017-11-29 16:47)