Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 multi file upload with PHP

Tags:

html

php

Here is the code I have, and I'm wondering what I'm doing wrong that it doesn't display the name.

<form action = "self.php" method="post" enctype="multipart/form-data">
<input type="file" name="imageURL[]" id="imageURL" multiple="" />
<input type="submit" value="submit" name="submit" />
</form>

And the processing info that isn't working:

foreach ($_FILES['imageURL'] as $files[]) { 
    echo $files['file'];
}

Edit:

When changing my foreach loop to:

foreach ($_FILES['imageURL'] as $file) { 
    echo $file['name'];
}

Still nothing prints out.

However, when I do something like this:

foreach ($_FILES['imageURL']['name'] as $filename) { 
    echo $filename;
}

The filename does print. I don't know what that implies though.



SOLVED UPDATE:

As linked to by John Conde, the array interlace structure is different when uploading multiple files than when uploading a single file. To use foreach, we must restructure the array.

$files=array();
$fdata=$_FILES['imageURL'];
if(is_array($fdata['name'])){
for($i=0;$i<count($fdata['name']);++$i){
        $files[]=array(
    'name'    =>$fdata['name'][$i],
    'type'  => $fdata['type'][$i],
    'tmp_name'=>$fdata['tmp_name'][$i],
    'error' => $fdata['error'][$i], 
    'size'  => $fdata['size'][$i]  
    );
    }
}else $files[]=$fdata;

NOW we can use foreach to loop:

foreach ($files as $file) { 
    echo $file['name'];
}
like image 512
kylex Avatar asked Jul 09 '10 18:07

kylex


2 Answers

Try

foreach ($_FILES['imageURL'] as $file) { 
    echo $file['name'];
}

UPDATE:

Google found this tutorial which may help you

like image 94
John Conde Avatar answered Oct 10 '22 00:10

John Conde


Instead of using for() and recounting the number of items in the array, you can use a more elegant foreach()

$files=array();
$fdata=$_FILES['file'];
if(is_array($fdata['name'])){
    foreach ($fdata['name'] as $i => $d) {
        $files[] = array(
        'name' => $d,
        'tmp_name' => $fdata['tmp_name'][$i]
        );
    }
}
else $files[]=$fdata;
like image 34
kotekzot Avatar answered Oct 09 '22 23:10

kotekzot