Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

checking file types in a perl upload script

by Bishma (Beadle)
on Feb 16, 2002 at 07:29 UTC ( [id://145822]=perlquestion: print w/replies, xml ) Need Help??

Bishma has asked for the wisdom of the Perl Monks concerning the following question:

A friend of mine gave me a simple file upload program. Here's the file proccessing part:
if ( $q->param() ) { my $filehandle = $q->param('file'); binmode($filehandle); open(OUT,">/var/www/html/toiletben/pictures/tempout") || die $!; binmode(OUT); # process $filehandle { my $buffer; while ( read($filehandle,$buffer,1024) ) { print OUT $buffer; } } close(OUT); print $q->header, $q->start_html, $q->p('File uploaded'), $q->end_html; exit(0); }
Unfortunatly it's mostly uncommented, but I've made sense of most of it. My question is this: I want this script to only accept .jpg files so I need to know how to make this test.

As I understand it, the buffer just recieves a binary stream containing the file itself. How can I test for the file type?

Replies are listed 'Best First'.
Re: checking file types in a perl upload script
by rob_au (Abbot) on Feb 16, 2002 at 08:28 UTC
    A simple search of this site would have revealed a number of nodes relating to CGI-based file upload, including one from myself here. This question could also have been answered by having a read through some of the documentation for CGI, specifically under the heading "Creating a file upload field".

    However, it should be noted, that you should not necessarily trust the extension of the file name supplied with the binary stream. As such, depending upon the intended application of the uploaded files, it would be wise to make use of a module such as File::MMagic (or the shell command file if installed), which allows for the identification of file types based upon file names and file content - This allows files to be verified that the file content type matches the name given.

     

    perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

Re: checking file types in a perl upload script
by kwoff (Friar) on Feb 16, 2002 at 08:24 UTC
    I assume you don't mean to match filename on /.jpg$/.

    If you read `perldoc -m Image::Size`, it shows what a JPEG header looks like.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://145822]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-28 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found