3

I am sending an array of files to php like this

<input type="file" name="image_name[]" />

But when I ask for 2 files for example and I foreach it, instead of 2 arrays with the file information it returns met 5 arrays of information with each array the file spec.

Foreach loop:

foreach($image as $key => $oneImage){
    print_r($oneImage);
    echo "<br />";
}

Output:

Array ( [0] => 3.jpg [1] => 5585_387497301371274_1740842451_n.png ) 
Array ( [0] => image/jpeg [1] => image/png ) 
Array ( [0] => /tmp/php8lgHOu [1] => /tmp/phpJOpJye ) 
Array ( [0] => 0 [1] => 0 ) 
Array ( [0] => 56405 [1] => 504664 ) 

If it isn't possible to get this as the array I would want it to be, how would I catch for example the tmp_name which is the third array? (Without having to make multiple foreach loops)

4
  • try to print_r($key) as well and you will be amazed ;) Commented Jun 15, 2013 at 19:47
  • I know that that does return the names of it but how can I catch those in the foreach? Like $oneImage['tmp_name'] Commented Jun 15, 2013 at 19:49
  • What does print_r($_FILES) return? Commented Jun 15, 2013 at 19:56
  • Array ( [auto_image] => Array ( [name] => Array ( [0] => 3.jpg [1] => 5585_387497301371274_1740842451_n.png ) [type] => Array ( [0] => image/jpeg [1] => image/png ) [tmp_name] => Array ( [0] => /tmp/phpn8wNQw [1] => /tmp/phpXh2RBM ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 56405 [1] => 504664 ) ) ) Commented Jun 15, 2013 at 20:00

1 Answer 1

1

When you upload an array of files the array returned is a little strange in it's structure, not the most intuitive in my opinion.

My solution is to use a for loop and not a foreach

My HTML:

<input type="file" name="image_name[]" />
<input type="file" name="image_name[]" />
<input type="file" name="image_name[]" />

My PHP:

<?php
$count = count($_FILES['image_name']['error']);
for ($i = 0; $i < $count; $i++)
{
    // image handling code here
    if ($_FILES['image_name']['error'][$i] ==  0)
    {
        move_uploaded_file($_FILES['image_name']['tmp_name'][$i], 'whatever.jpg');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow smart thinking! Thanks a lot I wouldn't have thought of this in years.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.