Validate individual files in multiple file upload before uploading them to server Validate individual files in multiple file upload before uploading them to server arrays arrays

Validate individual files in multiple file upload before uploading them to server


I think you can use validation at the client side to make the experience more smooth. as Mario pointed, you can use something like this to accept only mp3 files:

<input type="file" accept=".mp3" name="file_array[]" id="file_array[]" tabindex="1" required>

But since you can't trust user data, you must also add server side validation. For example:

if(isset($_FILES['file_array'])){$name_array = $_FILES['file_array']['name'];$tmp_name_array = $_FILES['file_array']['tmp_name'];$type_array = $_FILES['file_array']['type'];$size_array = $_FILES['file_array']['size'];$error_array = $_FILES['file_array']['error'];for($i = 0; $i < 3; $i++){    if ($i == 2){        if($type_array[2] != 'image/jpeg'){            echo 'Invalid file type: ' . $type_array[2];            break;        }     }    else {        if($type_array[$i] != 'audio/mp3'){            echo 'Invalid file type: ' . $type_array[$i];            break;        }    }    if(move_uploaded_file($tmp_name_array[$i],"../artists/$id/temp/".$name_array[$i])){        echo $name_array[$i]." upload is complete<br>";    } else {        echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";    }}}

Tested the above code and it seems to be working for me.

Notes:

if you already know the number of uploaded files don't use count since it could cause a risk, and if you want the number of uploaded files at a time to be variable, then make sure the count result doesn't exceed the max value. also use count outside of the loop so its only calculated once.

there are other more strict ways to validate file types, but this what I got now.

hope this helps and give feedback if I wronged in any how.


You can't, because the data is only available after upload. You may try to tell the browser (if capable) to send only specific mime-types using this:

<input type="file1" name="image" accept="image/*"><input type="file2" name="pdf" accept="application/pdf">