Perl Scripts ·

Perl CGI.pm File Uploads: upload(), Temp Files, Errors

By Manu Mathew, Technical Lead Engineer · Published 30 September 2013 · Last updated 5 October 2026

Isometric illustration of a document travelling into a server through a blue checkpoint gate

A file upload is one of the riskiest things a small Perl CGI script does: the file, its name and its type all come from the visitor. This note covers handling CGI.pm file uploads safely in Perl, from saving the file to limits, errors and temp files.

Quick answer

Call $q->upload('field') to get a file handle for an upload field. If it returns undef, check $q->cgi_error for the reason. Set $CGI::POST_MAX before creating the CGI object to limit the size, wrap CGI->new in eval to catch interrupted uploads, and never use the visitor’s file name as a path on your server.

This is the main note for CGI.pm uploads on this site. It replaces four older, shorter notes on temp files, interrupted uploads, upload hooks and checking the file type. CGI.pm left the Perl core in Perl 5.22, so install it from CPAN if use CGI fails. For ordinary form fields, see reading CGI.pm parameters safely.

How do I save an uploaded file?

#!/usr/bin/perl
use strict;
use warnings;
use CGI;

$CGI::POST_MAX = 5 * 1024 * 1024;    # refuse requests over 5 MB (set before CGI->new)

# CGI->new can die if the browser stops sending part-way through.
my $q = eval { CGI->new };
if (!$q) {
    print "Status: 400 Bad Request\r\nContent-Type: text/plain\r\n\r\nThe upload did not complete.\n";
    exit 0;
}

my $fh = $q->upload('document');      # undef if there is no valid upload
if (!$fh) {
    my $status = $q->cgi_error || '400 Bad Request';    # e.g. 413 when over POST_MAX
    print $q->header(-status => $status, -type => 'text/plain'), "Upload failed: $status\n";
    exit 0;
}

my $type = $q->uploadInfo($fh)->{'Content-Type'} // '';
if ($type ne 'application/pdf') {
    print $q->header(-status => '415 Unsupported Media Type', -type => 'text/plain'), "Please upload a PDF.\n";
    exit 0;
}

# Never build a path from the visitor's file name; choose your own.
my $target = sprintf '/srv/uploads/%d-%d.pdf', time, $$;
open my $out, '>', $target or die "Cannot write $target: $!";
binmode $fh;
binmode $out;
while (my $bytes = read($fh, my $buffer, 64 * 1024)) {
    print {$out} $buffer;
}
close $out;

print $q->header(-type => 'text/plain'), "Saved as $target\n";

I tested this with CGI.pm 4.68 on Perl 5.40. The Content-Type from uploadInfo is whatever the browser sent, so treat it as a hint; check the file contents too if it matters.

How do I check the type of an uploaded file?

Check both the type the browser claims, from uploadInfo, and the first bytes of the file itself.

# The type the browser claims, from the upload's headers
my $claimed = $q->uploadInfo($fh)->{'Content-Type'} // '';

# What the file actually starts with: every PDF begins with "%PDF-"
sub looks_like_pdf {
    my ($handle) = @_;
    binmode $handle;
    read($handle, my $magic, 5) // return 0;
    seek($handle, 0, 0);                  # rewind so the file can still be saved
    return $magic eq '%PDF-';
}

if ($claimed ne 'application/pdf' or !looks_like_pdf($fh)) {
    print $q->header(-status => '415 Unsupported Media Type', -type => 'text/plain'), "Please upload a PDF.\n";
    exit 0;
}

The Content-Type comes from the visitor’s browser and can be wrong or faked, so on its own it is only a hint. Most formats start with a fixed signature, such as %PDF- for PDF or \x89PNG for PNG. Rewind the handle after reading, or the saved file will be missing its first bytes. I tested this with CGI.pm 4.68 using real multipart requests.

What happens when an upload is too large or interrupted?

Can I use the temporary file directly?

Yes. CGI.pm writes each upload to a temporary file and deletes it when the program ends. $q->tmpFileName($fh) returns its path, which is handy for passing to another tool. If you move or reuse the file, do it before the script exits, or set $CGI::UNLINK_TMP_FILES = 0 and clean up yourself.

How do I show progress or skip the temp file?

Pass a callback to CGI->new. CGI.pm calls it repeatedly as data arrives; the third argument (0 here) turns off the temp file.

sub hook {
    my ($filename, $buffer, $bytes_read, $data) = @_;
    $data->{seen} = $bytes_read;    # store progress where a status page can read it
}

my %progress;
my $q = CGI->new(\&hook, \%progress, 0);

Why not use the uploaded file name?

The name comes from the visitor’s computer. It can contain paths (C:\Users\me\report.pdf), ../, or characters your file system dislikes. Generate your own name, and if you want to keep the original, store it as data rather than using it as a path.

Frequently asked questions

Is CGI.pm still a good choice for file uploads?

It is maintained and works, but it is no longer part of core Perl, and its own documentation points new projects towards modern frameworks. For an existing CGI application, keep CGI.pm up to date, set a size limit and check every file. Plan a move to a modern setup when the application grows.

Does the form need anything special for uploads?

Yes. The form must use method="post" and enctype="multipart/form-data", and the field must be type="file". Without that enctype, the browser sends only the file name as text, so upload() returns undef even though the field looked filled in.

How do I limit uploads to certain file types?

Allow a short list of extensions you expect, check the first bytes of each file against the matching signatures, and reject everything else. Don’t rely on the browser’s Content-Type alone, because the visitor controls it. Save files outside the web root so an uploaded script can never run.

Where should uploaded files be stored?

Outside the web server’s document root, in a folder the script can write to but the web server will not execute or list. Give each file a name you generate, keep the original name in a database if you need it, and serve files back through a script that checks permissions.

Related notes: Perl CGI.pm basics; Perl files, folders, CSV and downloads; checking whether a Perl variable is a number; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

An earlier version of this note reproduced sections of the CGI.pm documentation. This version is rewritten in my own words, with new examples.

Sources: CGI.pm documentation: Processing a file upload field; perl5220delta: CGI.pm removed from core.

Back to the blog