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

Hi, Is there a way in perl or just a perl module that allows me to get the file extension of a file(such as .jpg, .pdf, .html, etc.) when ppl upload a file?

Replies are listed 'Best First'.
Re: filetype extension query
by runrig (Abbot) on Aug 31, 2001 at 23:55 UTC
      I would also use File::Basename.

      Sample use:

      use strict; use File::Basename; my $mFileName; my $mFilePath; my $mFileExt; foreach ( '/home/rhose/work/perl/test', '/home/rhose/work/perl/test.pl', 'c:\work\perl\test', 'c:\work\perl\test.pl' ) { ($mFileName, $mFilePath, $mFileExt)=fileparse($_,'\.[^.]*'); print "Full:\t",$_,"\n"; print "Path:\t",$mFilePath,"\n"; print "Name:\t",$mFileName,"\n"; print "Ext:\t",$mFileExt,"\n"; print "\n"; }
Re: filetype extension query
by tachyon (Chancellor) on Sep 01, 2001 at 00:06 UTC

    Assuming they supply an accurate name:

    $filename = "/foo/bar/myfile.txt"; ($ext) = $filename =~ m/\.(\w+)$/; print $ext;

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: filetype extension query
by thpfft (Chaplain) on Sep 01, 2001 at 03:47 UTC

    If you just want to make sure that the file you store has the same suffix as the uploaded file, then you're on the right track.

    However, if you need is to identify the type of file uploaded and act on it accordingly, you might be better off using the mime type than the file extension. clients with macs will be pretty loose with the extensions, for example.

    with CGI.pm to handle the uploads - you are using CGI.pm to handle the uploads, aren't you? - then it's easy:

    my $filename = $query->param('upload_field'); my $type = $query->uploadInfo($filename)->{'Content-Type'};

    Which will give you something like 'image/gif' or 'text/html'. You can derive a file suffix from the second part in a fairly reliable way, but you might need to map from /text to .txt and /jpeg to .jpg, and so on.

    For images, by the way, you can also get a very reliable indication of the type from the absurdly useful Image::Size module:

    use Image::Size; my $filename = $query->param('upload_field'); my ($width, $height, $type) = imgsize($filename);

    Which will give you a plain 'gif' or 'jpg' or 'png' or 'swf', but doesn't work for anything else.