in reply to Verifying File Type Using Only Modules from basic distribution of Perl

A quick-and-dirty method, though not 100% reliable, is to look for certain header signatures in the file. For example, GIF files begin with the characters "GIF", JPEG files contain "JFIF" at byte offset 6, and PNG files have "PNG" at offset 1. So, you could do something like this:
sub what_is { my ($file) = @_; my $header; open (FILE, $file) || return; read (FILE, $header, 12); # Read first twelve bytes close (FILE); return unless (length($header) == 12); return "GIF" if (substr($header,0,3) eq "GIF"); return "JPEG" if (substr($header,6,4) eq "JFIF"); return "PNG" if (substr($header,1,3) eq "PNG"); return; }
This worked well when I had to verify that the "GIF" files being sent to me were actually GIFs, and not just Photoshop PSD files with a ".gif" extension. It's not foolproof, since there may be an error in the image, or the key text just might appear there coincidentally.
  • Comment on Re: Verifying File Type Using Only Modules from basic distribution of Perl
  • Download Code