Click to See Complete Forum and Search --> : [RESOLVED] Checking File Extension
dclamp
Jun 2nd, 2007, 07:19 PM
i have some code that checks to see if the file ext is a valid picture that we support. The problem is that it is a valid extension, but it returns that it isnt.
here is my code:
$image = $_FILES['image_file']['tmp_name'];
$memberid = $_SESSION['member_id'];
$pos = strrpos($image, '.');
$ext = substr($image, $pos, strlen($image) - $pos);
if($ext!="jpg"&&$ext!="jpeg"&&$ext!="png"&&$ext!="tif"&&$ext!="gif") {
$error[2] = "The file you selected is not supported by our system.";
}
penagate
Jun 2nd, 2007, 08:27 PM
I can't really read that code, but try this instead.
$valid_extensions = array(
'jpg',
'jpeg',
'png',
'tif',
'gif'
);
if (!in_array(pathinfo($image, PATHINFO_EXTENSION), $valid_extensions))
$error[2] = 'The file you selected is not supported by our system.';
You should bear in mind that extensions aren't reliable; you should also perform some sort of validation upon the file itself. For images, this can be done by attempting to load it using the GD library.
NPassero
Jun 6th, 2007, 03:05 PM
i would just use the explode function..
just recently did this:
$file = explode(".", $_FILES['image_file']['tmp_name'] );
// returns
// $file[0] = filename
// $file[1] = .fileEXT
$extension = $first[1];
// Then compare to the available extensions
penagate
Jun 6th, 2007, 08:03 PM
And what if the filename contains multiple dots?
Besides, you've used $file[0] twice in your code (should the second one be $file[1]?), and $first[1] after that (where does $first come from?). Oh, and you're missing a comma between the arguments for explode().
If there is a function available that does what you need, it is advisable to use that, rather than use other functions to achieve the same thing. For one, it makes the code more readable; you don't have to pepper it with comments such as 'explode the filename to get the file extension'. It also is shorter and has less chance of error.
dclamp
Jun 6th, 2007, 11:33 PM
thanks you guys for your help!
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.