What are cookies?
It would be risky to allow web sites to access files on a user's computer because malicious web sites could access users' personal data. Cookies are stored inside a web browser, so web sites can store information in them without needing access to files. Any malicious data put into cookies is contained and can't do any damage.
How do web servers set cookies?
Cookies are set and accessed by web servers when a user loads a page. When a web server receives a request from a web browser, it sends HTTP headers back to the browser, and then it sends the page that was requested. The HTTP headers are a series of text parameters sparated by carriage return and line feed characters. Cookies are set using the Set-Cookie parameter.
In a script, the simplest way to set headers is to print them before sending any other data. You must make sure there is an empty line after the headers and before the page content, hence the double "\r\n" at the end of the last header field:
#!/usr/bin/env python print 'Content-Type: text/html\r\n' print 'Set-Cookie: raspberrypi="Hello world"; \ expires=Wed, 28 Aug 2013 18:30:00 GMT\r\n\r\n' print """ <html> <body> <h1>Some web page</h1> </body> </html> """
Cookies have a name and a value. In the example above, the name of the cookie that's set is raspberrypi, and its value is "Hello world". They can have other attributes including:
- domain: the domain name of the site setting the cookie,
- path: the path that set cookie, or the path where a cookie is relevant,
- expires: the expiry date when browsers should delete the cookie,
- secure: if this field is set, the cookie should only be retrieved from a secure server using HTTPS. This ensures that cookies are encrypted when they are sent.
Setting cookies with Python
Python provides a library for handling cookies. The example below shows how to create a cookie, assign a value to it, and assign a value to the 'expires' attribute:
#!/usr/bin/env python import Cookie # create the cookie c=Cookie.SimpleCookie() # assign a value c['raspberrypi']='Hello world' # set the xpires time c['raspberrypi']['expires']=1*1*3*60*60 # print the header, starting with the cookie print c print "Content-type: text/html\n" # empty lines so that the browser knows that the header is over print "" print "" # now we can send the page content print """ <html> <body> <h1>The cookie has been set</h1> </body> </html> """
After the cookie has been set up, instead of having to print the Set-Cookie directive explicitly, we can just print the variable c. In this example, the expires time is set to 10,800 seconds (3 hours) from the time the cookie was set. You can execute this script by following this link (if your browser has cookies enabled, this script will set a cookie in your bowser that contains the string "Hello world"):raspberrywebserver.com/cgi-bin/examples/cookies.py
See this page on Wikihow that shows you how to view cookies in different browsers.
You can see what the HTTP headers look like by using the wget command, which is usually used to download files from web sites. This command can be told to save headers using the --save-headers option:
This command will create a file called cookies.py in the directory where the command was run. If you open the file in a text editor, you'll see the headers followed by the content produced when the script is executed on a server.
If you save data in cookies, you need to be able to retrieve that data. The following script will check to see if a cookie has been set in a browser:
#!/usr/bin/env python import os import Cookie print "Content-type: text/html\n\n" print """ <html> <body> <h1>Check the cookie</h1> """ if 'HTTP_COOKIE' in os.environ: cookie_string=os.environ.get('HTTP_COOKIE') c=Cookie.SimpleCookie() c.load(cookie_string) try: data=c['raspberrypi'].value print "cookie data: "+data+"<br>" except KeyError: print "The cookie was not set or has expired<br>" print """ </body> </html> """
The Python cookie library is used to create a cookie variable, and then the load function is used to get the cookie contents from the browser. Once it's been loaded the data contained in the cooke can be accessed. Clicking on the following link will execute the script and see if the cookie is set on your computer:raspberrywebserver.com/cgi-bin/examples/checkcookie.py
Cookies can be cleared by setting their expires time to some time in the past. It's conventional to set them to midnight Thursday 1st January 1970. Web servers can't force browsers to clear cookies; they can only suggest that a browser deletes a cookie. Whether or not a cookie is actually deleted is up to the browser.
This script sets the expires time of a cookie in the past so that the cookie will be cleared:
#!/usr/bin/env python import Cookie import cgi # set the cookie to expire c=Cookie.SimpleCookie() c['raspberrypi']='' c['raspberrypi']['expires']='Thu, 01 Jan 1970 00:00:00 GMT' # print the HTTP header print c print "Content-type: text/html\n\n" print """ <html> <body> <h1>The cookie has been set to expire</h1> </body> </html> """
It also sets the value of the cookie to an empty string in case the browser doesn't delete the cookie. Click this link to clear the cookie from your browser (note that this works better in some browsers than others):raspberrywebserver.com/cgi-bin/examples/clearcookies.py
See also: http://en.wikipedia.org/wiki/HTTP_cookie.