tags:

views:

51

answers:

4

So in PHP, I am checking a file extension against multiple types to get the general type of file

so here is what I have for images alone:

if ( $ext == "bmp" || $ext == "jpg" || $ext == "png" || $ext == "psd" || $ext =="psp" || $ext == "thm" || $ext == "tif" || $ext == "ai" || $ext == "drw" || $ext == "eps" || $ext == "ps" || $ext == "svg" || $ext == "3dm" || $ext == "dwg" || $ext == "dxf" || $ext == "pln" )

I know that is crazy unefficient, considering the number of if-elses I'll also need to use. Is there another way of doing this to check files, or maybe a better, premade function (like apaches mime_Magic)? thanks for the help!

+6  A: 

To solve just this problem, you can do:

if(in_array($ext, $extensions))

and put those extensions in an array. Be sure you're checking the actual mimetype of the file, as well, rather than just blindly trusting the extension.

Matchu
Cool! thanks! What is the best method of getting mimetype? I am seeing a few!
Kyle
Doing a bit of searching on SO (for "php file upload secure" and the like) I found this neat tip from Pekka: after doing basic checks that it's an image file, use `imagecopy` to remove anything bad like PHP code that could be run by your having left a bad `include()` somewhere. That almost ensures that your image can't possibly have anything really all that bad in it, which is really the only issue: forgery.
Matchu
+1  A: 

Mime content type, Fileinfo functions

dev-null-dweller
A: 
   preg_match("/bmp|jpg|png|psd|psp|thm|tif|ai|drw|eps|ps|svg|3dm|dwg|dxf|pln/",$ext,$matches);
   print $matches[1];
ghostdog74
Whoa now, looks like that'll match a file name like "modest_pln" with no extenton type.
Tchalvak
the OP's $ext already has the extension. Look at the way he compares the variable.
ghostdog74
+2  A: 

Use something like this

$extensions = array("bmp", "jpg", "png", "psd", "psp", "thm", "tif", "ai", "drw", "eps", "ps", "svg", "3dm", "dwg", "dxf", "pln");
if (in_array($ext, $extensions))
tig