Perl CGI  «Prev  Next»

Lesson 9Cookies
ObjectiveIdentify how a cookie works.

Identify Perl Cookie Functionality

In the guestbook example, we saw how to use hidden fields to maintain the state and context of a user's session.
Hidden fields are useful for maintaining the state of a session, but what of the situation where a user wants to return to your site at a later time? Perhaps after days or weeks? Netscape created its cookies specification for this exact purpose.
Netscape's Persistent Client State HTTP Cookies specification documents a convention for saving persistent-state information in the client. This allows the client to return to a Web site at a later time and still maintain context from a previous session.

RFC-2109 cookies are different from Netscape cookies.

How cookies work

Cookies work by sending headers back and forth over the HTTP connection. When you want to set a cookie in the browser, the server must send a Set-cookie: header to the browser along with all the other headers it normally sends with the HTTP response.
When the client then connects back to that same site, it will send whatever cookies it has for that site in a Cookie: header when it sends its HTTP request to the server.
The cookie is set from the server with a header like this:
Set-cookie: UserID=007

And, when the same browser connects back to that same site it sends the cookie like this:
Cookie: UserID=007


Sessions

HTTP is, by design, a stateless protocol. This means that each request is independent of every other request. In the early days of the web, every time you visited a web page, the server had no idea you had been there before. Then a Netscape employee named Lou Montulli had the brilliant idea to take magic cookies (no, not the type you buy in Amsterdam), which were already in use in other software, and implement them in Netscape Navigator, a browser popular back in the mid-to-late 1990s. This was one of the most important events in the history of the web. Now, if a browser returns a cookie to a host, the host can know that the user had previously visited. In the code that follows, Plack::Session uses cookies to pass a session key back and forth between the Plack software and the client. The Plack software uses the value of the cookie to look up its in-memory session data. Because this data is not persistent, it cannot survive between server restarts. In serious Comp applications, session data is generally saved in a persistent state, such as in a database or memcached.
In the next lesson, we will see an example of how a cookie is set and retrieved.

SEMrush Software