Input with GET method

This pages shows how to obtain and parse user input from the GET method.

Programming Issues

With the HTTP GET method, user input is passed to the CGI script via the QUERY_STRING environment variable.

User input is URL encoded, which entails the following:

There are therefore three stages to getting the user input into a usable form:

These stages are not necessarily distinct, as we will see.

Here is how our CGI script accomplishes the task:

Aside from outputting a table with our name/value pairs, that's all there is to it!

Note than when submitting data from a form, your browser will automatically create an appropriate URL, complete with query string, using the name attribute of your form controls and either the value attribute or the value entered by the user.

For our purposes, we also exit the script if the GET method is not used, or if the QUERY_STRING environment variable is empty. Since the whole point of this script is to demonstrate parsing the query string, which is only passed with the GET method, we are at perfect liberty to reject any other form of input.

As a final note, when you run the script you'll see that Perl doesn't sort associative arrays by name; they are deliberately randomised to help search efficiency. Thus, although you may see name/value pairs in the order name1, name2 and name3, they won't necessarily output in that order. Of course, if we wanted to manually sort them in any particular way, we could do so easily.

Usage

You can call the script directly, using URLs such as the following (which include some badly formed URLs — marked with * — as examples):

You can also call it from a form, such as the one below:

Type your favourite word:
Choose a fruit:
Which is best?

Choose all the languages you know:


Type something interesting:

Note that we end up with multiple values in the "langsknown" variable because we have used the same name attribute for each of the check boxes. In the CGI script, we have used "---" as the multiple separator, but in practice we would probably use \0 in case the user actually entered "---". Using \0 also allows us to treat langsknown as a Perl list if we want to do that.

Also note that the POST method is more appropriate than GET for some forms. There are two reasons for this:

Source and Downloads