Maintaining State

One of the first complications for any nontrivial CGI script is how to “maintain state.” Since HTTP is a stateless protocol, there’s no built-in mechanism for keeping track of requests from the server end. A CGI transaction involving multiple forms, therefore, needs to find a way to remember information supplied on previous forms. One way to deal with this issue is to use cookies, which allow the CGI program to save information on the browser’s end. HTTP Cookies are described in Chapter 17. CGI.pm uses the cookie( ) method to set and retrieve cookie information from a client.

CGI.pm implements other ways of maintaining state without cookies. To move around within a document containing form information, you can use the self_url( ) method to get a URL for the current document that saves the current form information. More generally, you can save query information from sessions in a variety of ways by saving to a filehandle with $query->save( ). This method provides the pathway to connecting client sessions with outside data sources like databases and user directories.

Get Webmaster in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.