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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)