如何上传多个文件?

I am trying to make a multiple image uploader. The file upload fields are being added in the form dynamically using jquery. I tried making an array of the fields since I don't want to have a hidden field. so my generated upload fields look like

<input type="file" id="img0" name="img[]"/>
<input type="file" id="img1" name="img[]"/>
<input type="file" id="img2" name="img[]"/>
.....
..

And on the php side I did something like

if(isset($_FILES['img']))
{
    foreach($_FILES['img'] as $k=>$v)
    {
        if($v!="")
        {
            uploadImage($k,0,0,0,"content/gallery/");
        }
    }
}

Now I know I am way too wrong, since in that code I am looping through the 'img' file's properties instead of all images....but I have no idea how to fix this.

PS: uploadImage is a function I wrote which expects the file input field's name as the first parameter.

Why don't you use unique names instead and just loops through $_FILES instead? I'm assuming you don't post any other files...

Otherwise, try a regular for() loop with index instead, since you are iterating over the file-objects properties. Also, you are passing the $key into the upload function, not the $value, I'm guessing that's one obvious mistake.

Can't you do something like:

$target_path = 'uploads/';

foreach($_FILES as $file) {
    $target_path = $target_path . basename( $file['name']); 

    if(move_uploaded_file($file['tmp_name'], $target_path)) {
        echo 'The file '.  basename( $file['name']). ' has been uploaded';
    } else{
         echo 'There was an error uploading the file, please try again!';
    }
}

Just to be sure:

Don't forget to add enctype="multipart/form-data" to you form.

$rtn = array();
foreach ($_FILES['img'] as $key=>$val)
{
  foreach ($val as $fkey=>$fval)
  {
    $rtn[$fkey][$key] = $fval;
  }
}
print_r($rtn);

You're close, but the structure of $_FILES is not really intuitive and kind of backwards from what one might expect. To send the names of the uploaded files to your function, do this:

if (isset($_FILES['img']))  {
    print_r($_FILES)  // Just to see the $_FILES array's structure (testing only)
    foreach ($_FILES['img']['name'] as $k => $v)  {        // 'name' is an array
        if ($v != '')  {                                   // Each value of $v is a file name
            uploadImage($v, 0, 0, 0, 'content/gallery/');  // Change $k in your code to $v
        }
    }
}

Well at last I used hidden input field to pass the total number of images being uploaded, and uploaded them using their names

yeh I gave up on using arrays.....This array approach was a lot more work than it's worth.

One better option I can suggest -

jquery File Upload Plugin Demo URL - http://blueimp.github.com/jQuery-File-Upload/ Source Code - https://github.com/blueimp/jQuery-File-Upload