Sending Input to a CGI Script
Though preset environment variables provide much information, we would like to be able to supply any type of data to our CGI scripts, such as a user's name or a search-engine query. The environment variable QUERY_STRING provides a mechanism to do just that. The QUERY_STRING variable contains information that is appended to a URL in a get request. For example, the URL
www.somesite.com/cgi-bin/script.cgi?state=California
causes the Web browser to request a CGI script (cgi-bin/script.cgi) with query string (state=California) from www.somesite.com. The Web server stores the query string following the ? in the QUERY_STRING environment variable. The query string provides parameters that customize the request for a particular client. Note that the question mark (?) is not part of the resource requested, nor is it part of the query string. It serves as a delimiter (or separator) between the two.
Figure 19.9 shows a simple example of a CGI script that reads data passed through the QUERY_STRING. The data in the query string can be formatted in a variety of ways. The CGI script reading the query string must know how to interpret the formatted data. In the example in Fig. 19.9, the query string contains a series of name-value pairs delimited by ampersands (&), as in name=Jill&age=22.
Figure 19.9. Reading input from QUERY_STRING.
(This item is displayed on pages 929 - 930 in the print version)
In line 16 of Figure 19.9, we pass "QUERY_STRING" to function getenv, which returns the query string or a null pointer if the server has not set a QUERY_STRING environment variable. [Note: The Apache HTTP Server sets QUERY_STRING even if a request does not contain a query stringin this case, the variable contains an empty string. However, some servers, such as Microsoft's IIS, set this variable only if a query string actually exists.] If the QUERY_STRING environment variable exists (i.e., getenv does not return a null pointer), line 17 invokes getenv again, this time assigning the returned query string to string variable query. After outputting a header, some XHTML start tags and the title (lines 1929), we test if query contains data (line 32). If not, we output a message instructing the user to add a query string to the URL. We also provide a link to a URL that includes a sample query string. Query string data may be specified as part of a hyperlink in a Web page when encoded in this manner. The contents of the query string are output by line 36.
This example simply demonstrated how to access data passed to a CGI script in the query string. Later chapter examples show how to break a query string into useful pieces of information that can be manipulated using separate variables.