Writing a CGI upload form

Writing a CGI upload form

In this tutorial you will learn how to write a perl CGI form that allows the uploading of files from a user’s PC to the server on which your CGI script is running. If you have never done any perl CGI programming before, we suggest you first look at the CGI Tutorial and CGI Forms Tutorial.

Firstly you need to ensure that you have access to a web server (that has perl installed), that it has cgi enabled, and that you can put your perl script into the cgi directory.

Starting your script

Like a standard perl CGI form we use the CGI module to output the HTML. We
take advantage of the CGI module’s POST_MAX variable to set an upper limit
on the size of files that we will allow to be uploaded. We also turn on
taint checking with the -T switch.

Starting the form

Because we are uploading a file we need a multipart form rather than a standard form:

Or alternately:

The upload field

Using the object oriented CGI methods, you can output a form upload field like this:

While you can specify a default value for the filename to be uploaded, at present no browsers will honour it, as it’s considered a possible security problem. In the same respect you can’t alter the value of the field from JavaScript.

Let’s add a submit button for a complete form:

Uploading the file

Later on in your code that handles the submitted form values, you need to
upload the file. Here’s a code fragment that uploads the user’s file in 1024
byte chunks, using the read() function. Note also that we use the three
argument form of open() which lets us specify the file open mode (‘>’),
separately and ensures that any characters that are special to the shell
(such as ‘>’ and ‘|’) appearing in the filename argument, are treated literally.

Working example

Realistically you’ll want more functionality than we’ve shown so far. For example, you probably don’t always want to write the file to “/tmp/uploaded” and
you’re advised to use taint checking to ensure that the filename supplied by
the user matches a regular expression of allowable characters. Your notion of
what is allowable or safe will depend on your circumstances and also on the
web server operating system. The following example (which assumes a Unix like
web server operating system), is a working example of a cgi script that will
upload files to the /tmp directory.

See also

Scroll to Top