upload method not returning undef?

S

Suk

Hi

I'm tinkering with a simple file upload script

I want to be sure that if a user enters an invalid filename (i.e one
that doesnt exist) in a webform an error is returned. In the CGI
documentation it says the upload( ) method should return undef for an
invalid filehandle, but I cant seem to get this to work:

Here is the script im using:-

#!/usr/local/bin/perl
use strict;
use warnings;
use CGI qw:)standard);

our $upload_dir = "/tmp";
our $filename;
our $upload_filehandle;
our $message="Thank you";

$filename = param("file");
$filename =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = upload("file");

die "Invalid filehandle" if (!defined($upload_filehandle));

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
print UPLOADFILE;
}

close UPLOADFILE;

print header;
print <<END_HTML;
<HTML>
<HEAD>
<TITLE>Thank you for your upload</TITLE>
<script type="text/javascript">
alert("$message");
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
END_HTML

The "die" seems to be ignored, and I get an empty file in /tmp if I
enter a non-existent file in the webform?
 
G

Gunnar Hjalmarsson

Suk said:
I want to be sure that if a user enters an invalid filename (i.e one
that doesnt exist) in a webform an error is returned. In the CGI
documentation it says the upload( ) method should return undef for an
invalid filehandle,

The handle isn't necessarily invalid if the file is empty.
Here is the script im using:-

#!/usr/local/bin/perl
use strict;
use warnings;
use CGI qw:)standard);

our $upload_dir = "/tmp";
our $filename;
our $upload_filehandle;
our $message="Thank you";

$filename = param("file");
$filename =~ s/.*[\/\\](.*)/$1/;

$upload_filehandle = upload("file");

die "Invalid filehandle" if (!defined($upload_filehandle));

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
print UPLOADFILE;
}

close UPLOADFILE;

You may want to try something like this here:

unless ( -s "$upload_dir/$filename" ) {
unlink "$upload_dir/$filename";
die "Invalid filename";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top