Search code examples
phpfile-uploadmultiple-file-upload

Issues with Uploading Multiple files with PHP


I can see this question has been asked a million times before. I have been through many of the responses and can't seem to get it right:-

I am simply trying to upload multiple files. I'm certain that the form is correct. The issue I get is that if I use a foreach loop, PHP cycles through 5 times (I guess once for each key in $_FILES).

I have read that you should count the uploaded files in the $_FILE['file_upload'] array, then use a for loop, and include an index on the end, such as:-

$_FILES['file_upload']['name'][$1]

however, when I try to access those values I only get the first letter of the value (I think I understand why this is).

The only thing I can think is to use

for($i ; $i<$size ; $i++){...}

and then nest a foreach loop inside it, however, this seems inefficient and I've seen no other suggestions to this end.

I would therefore be eternally grateful if someone could set me straight once and for all. My code is here:-

foreach ($_FILES['file_upload'] as $key => $value){    
    $tmp_file = $_FILES['file_upload']['tmp_name'];
    $target_file = basename($_FILES['file_upload']['name']);  

    if(move_uploaded_file($tmp_file,$upload_location."/".$target_file)){
        $message = "File uploaded successfully";
    } else {
        $error = $_FILES['file_upload']['error']; // get the error
        $_SESSION['errors'][] = $error_msg[$error];// return the error that matches
    }// end if
} // end for

So just to clarify - The above code works and uploads the image, but where the loop cycles through 5 times (I'm assuming once per $_FILES attribute), I am getting 5 error messages.I hope this makes sense.

Many thanks in advance for any pointers

Phill


Solution

  • The following was taken from: PHP Manual

    <?php
    $uploads_dir = '/uploads';
    foreach ($_FILES["pictures"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
            $name = $_FILES["pictures"]["name"][$key];
            move_uploaded_file($tmp_name, "$uploads_dir/$name");
        }
    }
    ?>
    

    Which in turn you should be able to modify to something like this:

    <?php
    $uploads_dir = '/uploads';
    foreach ($_FILES["file_upload"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["file_upload"]["tmp_name"][$key];
            $name = $_FILES["file_upload"]["name"][$key];
            move_uploaded_file($tmp_name, "$uploads_dir/$name");
        }
    }
    ?>