Reading and writing cookies on the server-side

From Knowledge Kitchen
Jump to navigation Jump to search


Cookies are small key/value pairs stored by a server on the client computer. They are often used to track visitors and maintain sessions.

  • web servers instruct the client to store a cookie by issuing a special HTTP header, "Set-Cookie".
  • once cookied, every subsequent request by the client to that server will include the HTTP header, "Cookie" with the data that was stored.
  • by default, cookies are deleted when the user quits the browser. However, the server can instruct the client to keep them longer.

Reading a cookie

PHP example

The following example shows how the server can read the value of a cookie and use it to determine the content of the web page that is sent to the client.

 1  <!doctype html>
 2  <html>
 3  	<head>
 4  		<title>Get Cookie Values</title>
 5  	</head>
 6  	<body>
 7  		<h1>Get Cookie Values</h1>
 8  
 9  <?php if ($_COOKIE['has_visited_before'] == "yes") : ?>
10  
11  		<p>
12  			Your unique ID is <?php echo $_COOKIE['unique_id']; ?>
13  			<br />
14  			You've been here before!
15  		</p>
16  
17  <?php else : ?>
18  
19  		<p>Welcome for the first time!</p>
20  
21  <?php endif; ?>
22  
23  	</body>
24  </html>

Python example

The following example shows how the server can read the value of a cookie and use it to determine the content of the web page that is sent to the client.

 1  #!/usr/local/pkg/python/3.5/bin/python3
 2  
 3  import os
 4  
 5  print("Content-type: text/html")
 6  print()
 7  
 8  c = {} #blank dictionary of cookies
 9  
10  #check for cookies in the operating system's environmental variables
11  if "HTTP_COOKIE" in os.environ:
12  	#the os module stores cookies as a semi-colon separated string of key=value pairs
13      cookie_list = os.environ["HTTP_COOKIE"].split(";")
14      for cookie_string in cookie_list:
15      	#separate the key from the value
16      	key, value = cookie_string.split('=')
17      	c[key.strip()] = value.strip()
18  
19  #output the HTML
20  
21  print('''
22  <nowiki>
23  <!doctype html>
24  <html>
25  	<head>
26  		<title>Get Cookie Values</title>
27  	</head>
28  	<body>
29  		<h1>Get Cookie Values</h1>
30  ''')
31  
32  if c.get('has_visited_before', '') == 'yes':
33   	print('''
34   		<p>
35   			Your unique ID is {uid}
36   			<br />
37   			You've been here before!
38   		</p>
39  '''.format(uid=c.get('unique_id', '')))
40  
41  else:
42   	print('''
43   		<p>Welcome for the first time!</p>
44  ''')
45  
46  print(''' 
47   	</body>
48   </html>
49  ''')

Writing a cookie

PHP example

The following PHP code shows how the server can tell the client to store a few cookies on its behalf.

 1  <?php
 2  
 3  $randomId = rand() . time(); //generate a random id
 4  setcookie("unique_id", $randomId); //tell the browser to store a cookie
 5  setcookie("has_visited_before", "yes"); //tell the browser to store a cookie
 6  
 7  //set a cookie with a custom expiration date.. this cookie will self-destruct in year
 8  setcookie("semi-permanent-cookie", "here it is", time() + 3600*24*365);
 9  
10  ?>

Python example

The following Python code shows how the server can tell the client to store a few cookies on its behalf.

 1  #!/usr/local/pkg/python/3.5/bin/python3
 2  
 3  import random
 4  import datetime, time
 5  from http import cookies
 6  
 7  #make a blank cookie object
 8  c = cookies.SimpleCookie()
 9  
10  #set some cookies
11  random_id = random.randint(0,1000000000) + int(time.time()) #generate a random id
12  c["unique_id"] = random_id #tell the browser to store a cookie
13  c["has_visited_before"] = "yes" #tell the browser to store a cookie
14  
15  #set a cookie with a custom expiration date.. this cookie will self-destruct in year
16  expiration = datetime.datetime.now() + datetime.timedelta(days=365)
17  c["semi-permanent-cookie"] = "here it is"
18  c["semi-permanent-cookie"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S EST")
19  
20  print("Content-type: text/html;charset=utf-8")
21  print(c) #output the Set-Cookie HTTP response header
22  print("\n")

Deleting a cookie

To delete a cookie, simply set its expiration date to a time in the past.

PHP example

1  <?php
2  
3  //set a cookie with a past expiration date.. this cookie will be immediately deleted by the client
4  setcookie("semi-permanent-cookie", "here it is", time() - 100)
5  
6  ?>

Python example

 1  #!/usr/local/pkg/python/3.5/bin/python3
 2  
 3  import datetime, time
 4  from http import cookies
 5  
 6  #make a blank cookie object
 7  c = cookies.SimpleCookie()
 8  
 9  #set a cookie with an already-passed expiration date.. this cookie will self-destruct immediately
10  expiration = datetime.datetime.now() + datetime.timedelta(days=-1)
11  c["semi-permanent-cookie"] = "here it is"
12  c["semi-permanent-cookie"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S EST")
13  
14  print("Content-type: text/html;charset=utf-8")
15  print(c) #output the Set-Cookie HTTP response header
16  print("\n")

What links here