Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate PHP $_FILES array?

This might be stupid question, but PHPs array $_FILES has very odd format, which I have never used before. Can somebody tell me how can I iterate this array in sane way ? I have used to iterate objects or object like arrays, but this format is very odd for me. Is there any way to iterate this array like object array?

( [attachments] => 
    Array ( 
        [name] => Array ( 
            [0] => test1.png 
            [1] => test2.png 
        ) 
        [type] => Array ( 
            [0] => image/png 
            [1] => image/png 
        ) 
        [tmp_name] => Array ( 
            [0] => /tmp/phpmFkEUe 
            [1] => /tmp/phpbLtZRw 
        )
        [error] => Array ( 
            [0] => 0 
            [1] => 0 
        ) 
        [size] => Array ( 
            [0] => 9855 
            [1] => 3002 
        ) 
    ) 
)
like image 635
newbie Avatar asked Nov 28 '22 11:11

newbie


2 Answers

Wow, that indeed is odd, are you using <input type="file" name="attachments[]" /> in your markup? If you could afford to change those using unique name=, you won't have that odd format...

To directly answer your question, try:

$len = count($_FILES['attachments']['name']);

for($i = 0; $i < $len; $i++) {
   $fileSize = $_FILES['attachments']['size'][$i];
   // change size to whatever key you need - error, tmp_name etc
}
like image 52
Andreas Wong Avatar answered Dec 04 '22 23:12

Andreas Wong


I always thought that this structure was nonsense. So whenever I use a multiple input file field, I do this:

$files = array_map('RemapFilesArray'
    (array) $_FILES['attachments']['name'],
    (array) $_FILES['attachments']['type'],
    (array) $_FILES['attachments']['tmp_name'],
    (array) $_FILES['attachments']['error'],
    (array) $_FILES['attachments']['size']
);

function RemapFilesArray($name, $type, $tmp_name, $error, $size)
{
    return array(
        'name' => $name,
        'type' => $type,
        'tmp_name' => $tmp_name,
        'error' => $error,
        'size' => $size,
    );
}

Then you will have an array that you can iterate and each item in it will be an associative array of the same structure that you would get with a normal, single file input. So, if you already have some function for handling those, you can just pass each of these items to it and it will not require any modification.

By the way, the reason to cast all inputs as array is so that this will work even if you forgot to put the [] on the name of your file input (of course you will only get one file in that case, but it's better than breaking).

like image 20
Okonomiyaki3000 Avatar answered Dec 05 '22 00:12

Okonomiyaki3000