Curl and Cookies

I noticed the other day that the cheat sheet I have on this site for curl doesn’t show how to use cookies, so I thought I’d remedy that omission, and quickly! Being able to use the command line to authenticate and then go on and use part of a site behind a login box can be really handy, and it is also super-simple.

-c to Save a Cookie

Pass the -c switch followed by a filename and curl will write the cookies to a file. This is the “cookie jar” and you can dip into it whenever you want to send the cookies back with a future request. For example:
curl -c cookies.txt http://www.lornajane.net
This writes a file named cookies.txt to the local directory. When I look in it, it contains:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

www.lornajane.net FALSE / FALSE 0 s9y_4e071c5ccc553288993faf0369cb076c 539e01676501366ea0f04e2646b1a31d

-b to Send Cookies

All I do when I want to use the cookie on future requests is pass exactly the same command but with a -b switch; this will read the named file and send the cookies along. You can edit the cookies as you wish, at your own risk of course, and this makes the use of cookies and curl an absolutely invaluable technique for testing! It’s also common to use it on sites where you want to download a file directly to the server but the site requires login first.

7 thoughts on “Curl and Cookies

  1. I have a scribbled sheet on my desk, which is my “cheat sheet” for curl, its really short and I thought I’d put my notes here for safe-keeping. If you’re visiting, then I hope they help you too. Curl from command line Curl is a way of making web re

  2. Thanks for posting this. I had been searching for quite some time.

    If you use ZF (Zend Framework), the “cookie jar” implementation/class might be somewhat helpful, too (depending on what you’re trying to do, of course) :-)

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.