Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Looping through $_FILES to check filetype

My first question on SO, thanks. :)

I'm developing a support issue logging system for my company and it must allow for files to be uploaded aswell as any problems submitted to our database. There could be from 0-6 different uploads to check, along with a support issue. I've managed to get an accurate variable of how many files there is through having a hidden input field (imgcount) that updates via js whenever an image is selected through a type="file" input, or removed from the form.

My [input type="file"] names are image1, image2, etc. As i thought it'd be easier this way to loop through them.

When the form is submitted the following code takes a look to see if there's any files and checks that they're of valid type (gif/jpeg/png), so they can be uploaded safely. I'm not too worried about viruses as the support system has a nice secure logon and we trust our clients.

$sscount = $_POST['imgcount'];
echo $sscount; //to test the variable
if($sscount>0){
    for($i = 1; $i <= $sscount; $i++){
        if (($_FILES["image$i"]["type"] == "image/gif")
        || ($_FILES["image$i"]["type"] == "image/jpeg")
        || ($_FILES["image$i"]["type"] == "image/png" )
        && ($_FILES["image$i"]["size"] < 500000))
        {

        }
        else
        {
        $errormsg .= "Error: Image $i must be either JPEG, GIF, or PNG and less than 500 kb.<br />";
        }
    }
}

But this doesn't seem to be looping through correctly, anyone got any ideas how i can get it to loop through and return correctly?

like image 568
Stann0rz Avatar asked Jul 17 '09 14:07

Stann0rz


1 Answers

The && operator has a higher precedence than ||, so rather than (A OR B OR C) AND D as you intended, it is actually A OR B OR (C AND D)

You can use parentheses to enforce the evaluation you intended.

However, something like this might be cleaner and easier to maintain/read:

$allowed_types=array(
    'image/gif',
    'image/jpeg',
    'image/png',
);


$sscount = $_POST['imgcount'];
if($sscount>0){
    for($i = 1; $i <= $sscount; $i++){

        if (in_array($_FILES["image$i"]["type"], $allowed_types) && 
            ($_FILES["image$i"]["size"] < 500000))
        {

        }

    }
}
like image 86
Paul Dixon Avatar answered Sep 20 '22 23:09

Paul Dixon