How can I keep "state" information between calls to my CGI program?

Using Hidden Form Fields

One valid approach is to use hidden fields in forms. For example:
<INPUT TYPE=hidden NAME=state VALUE="hidden info to be returned with form">
By now, most browsers can handle the hidden type, but understand that some browsers will fail to hide the field (and probably confuse the user). Note that "hidden" doesn't mean "secret"; the user can always click on "view source."

The ugliness of a "hidden" field appearing on a browser that doesn't understand hidden fields can be minimized by setting SIZE=0 for that attribute.

Using PATH_INFO

Another approach is to take advantage of the PATH_INFO environment variable. PATH_INFO contains any additional text in the URL that accessed the CGI program *after* the name of the CGI program itself. For instance, if your CGI program's URL is:

http://mysite.com/cgi-bin/mycgi

But you open the following URL instead:

http://mysite.com/cgi-bin/mycgi/Bob/27

The program "mycgi" will still be executed -- and the environment variable PATH_INFO will contain the text /Bob/27. You can take advantage of this by always outputting URLs that contain the state information you are trying to keep from one call to the next.

Keep in mind that URLs are limited to 1024 characters; browsers are not required to cope with more than that. If you need more, or dislike long URLs, simply keep the name of a temporary file in the PATH_INFO section of the URL and store information about that session in the temporary file.

Using HTTP "Cookies"

"Cookies" are a new mechanism, proposed by Netscape, which allows the browser to keep state information supplied to it by the server. The next time a request is made for a URL in a particular portion of the server, the relevant "cookie" will be sent to the server as part of the request! Cookies are currently implemented by Netscape and by Microsoft's Internet Explorer (2.0). By the time you read this more browsers may support them. But it is best to ensure that your pages are still usable without them.

See Netscape's Cookie Specification Page <URL:http://www.netscape.com/newsref/std/cookie_spec.html> for more information.


World Wide Web FAQ