Read more

How to use cookies with curl

Arne Hartherz
November 29, 2017Software engineer at makandra GmbH

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).

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2017-11-29 17:47)