I am trying to write a file that will handle the uploading of files in PHP, but I’m currently stuck in the logic part.
The issue I am having, and I searched around for this for days and cant find an answer, is that I want to be able to have a form that will allow single file uploads, and also multi-file uploads.
For example, the following form:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="image_1[]" multiple="multiple">
<input type="file" name="image_2">
</form>
In the example above, I want to allow image_1 to have multiple files, and image_2 to have only one.
What I cant figure out is how to check the files, since uploading them will give to different arrays, like this:
Array
(
[image_1] => Array
(
[name] => Array
(
[0] => file_1.pdf
[1] => file_2.pdf
)
[type] => Array
(
[0] => application/pdf
[1] => application/pdf
)
[tmp_name] => Array
(
[0] => /tmp/phpxrR9jO
[1] => /tmp/phpTLIOX5
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 164086
[1] => 151993
)
)
[image_2] => Array
(
[name] => file.pdf
[type] => application/pdf
[tmp_name] => /tmp/php9sLiBn
[error] => 0
[size] => 500065
)
)
I want to check the files for errors, size, type, etc. but I’m not sure how I can do this in an OOP way.
What i started writing but could actually write (because I don’t understand how this should work), is a main function that will loop through all of the files, and inside that loop, will call on other functions that will validate the file.
These other functions will check the files size, type, errors, etc.
What I cant figure out is how to do this when you have multi-file fields also.
Should I check if the file is a multi-file and then loop through it in each validator function, or should I loop through them before, and then call each validator function for that specific file value?
Or maybe I should convert the image_1 array into smaller arrays, or somehow group all names, types, tmp_names, etc.?