1This chapter discusses how one should manage sessions, that is, share state between multiple 2HTTP requests from the same user. We use a simple example where the user submits multiple 3forms and the server is supposed to accumulate state from all of these forms. Naturally, as 4this is a network protocol, our session mechanism must support having many users with 5many concurrent sessions at the same time. 6 7In order to track users, we use a simple session cookie. A session cookie expires when the 8user closes the browser. Changing from session cookies to persistent cookies only requires 9adding an expiration time to the cookie. The server creates a fresh session cookie whenever 10a request without a cookie is received, or if the supplied session cookie is not known to 11the server. 12 13@heading Looking up the cookie 14 15Since MHD parses the HTTP cookie header for us, looking up an existing cookie 16is straightforward: 17 18@verbatim 19FIXME. 20@end verbatim 21 22Here, FIXME is the name we chose for our session cookie. 23 24 25@heading Setting the cookie header 26 27MHD requires the user to provide the full cookie format string in order to set 28cookies. In order to generate a unique cookie, our example creates a random 2964-character text string to be used as the value of the cookie: 30 31@verbatim 32FIXME. 33@end verbatim 34 35Given this cookie value, we can then set the cookie header in our HTTP response 36as follows: 37 38@verbatim 39FIXME. 40@end verbatim 41 42 43@heading Remark: Session expiration 44 45It is of course possible that clients stop their interaction with the 46server at any time. In order to avoid using too much storage, the 47server must thus discard inactive sessions at some point. Our example 48implements this by discarding inactive sessions after a certain amount 49of time. Alternatively, the implementation may limit the total number 50of active sessions. Which bounds are used for idle sessions or the 51total number of sessions obviously depends largely on the type of 52the application and available server resources. 53 54@heading Example code 55 56A sample application implementing a website with multiple 57forms (which are dynamically created using values from previous 58POST requests from the same session) is available 59as the example @code{sessions.c}. 60 61Note that the example uses a simple, $O(n)$ linked list traversal to 62look up sessions and to expire old sessions. Using a hash table and a 63heap would be more appropriate if a large number of concurrent 64sessions is expected. 65 66@heading Remarks 67 68Naturally, it is quite conceivable to store session data in a database 69instead of in memory. Still, having mechanisms to expire data 70associated with long-time idle sessions (where the business process 71has still not finished) is likely a good idea. 72