11.02 Form Handling

Creating an Input Form

Reading the User's Form Input

When the user submits the form, your script receives the form data as a set of name-value pairs. The names are what you defined in the INPUT tags (or SELECT or TEXTAREA tags), and the values are whatever the user typed in or selected.

Users can also submit files with forms.

This set of name-value pairs is returned as one long string, which you need to parse. It's not very complicated, and there are plenty of existing routines to do it for you.

If that's good enough for you, skip to the next section. If you'd rather do it yourself, or you're just curious, the long string is in one of these two formats:




Just split on the ampersands or semicolons, then on the equal signs. Then, do two more things to each name and value:

  • Convert all “+” characters to spaces, and
  • Convert all “%xx” sequences to the single character whose ascii value is “xx”, in hex. For example, convert “%3d” to “=”.

This is needed because the original long string is URL-encoded, to allow for equal signs, ampersands, and so forth in the user's input.

So where do you get the long string? That depends on the HTTP method the form was submitted with:

For GET submissions, it's in the environment variable QUERY_STRING.

For POST submissions, read it from STDIN. The exact number of bytes to read is in the environment variable CONTENT_LENGTH.

(If you're wondering about the difference between GET and POST, see the footnote discussing it. Short answer: POST is more general-purpose, but GET is fine for small forms.)

Sending the Response Back to the User

First, write the line

Content-type: text/html

plus another blank line, to STDOUT.

After that, write your HTML response page to STDOUT, and it will be sent to the user when your script is done. That's all there is to it.

Yes, you're generating HTML code on the fly. It's not hard; it's actually pretty straightforward. HTML was designed to be simple enough to generate this way.

If you want to send back an image or other non-HTML response, here's how to do it.

That's it. Good Luck!

See how easy it is? If you still don't believe me, go ahead and write a script. Make sure to put the file in the right place on your server, and make it executable; see this footnote for more hints.

Before you write too many scripts, learn about CGI security issues.

lynplex/lp1102.txt · Last modified: 2012/09/08 11:49 (external edit)