Question : Handling multipe file uploads using PHP (using jquery multi-file upload javascript)

I'm using Jquery's multi-file upload script on a site that I'm developing:

http://www.fyneworks.com/jquery/multiple-file-upload/

The script allows me to upload multiple files PER file upload field, and was very easy to implement.  However, no examples are provided on how to handle the files uploads on the server side, and that's where I'm running in to some difficulty. (I'm using PHP, btw)

My multiple file upload fields in the form are all named as follows:

upload_55
upload_56
upload_57
(etc.)

The numbers that I'm appending to each field name correlate to database record ID values.  I am also passing this list of ID values (as an array) to the form handler in a hidden form field:

echo '<input type="hidden" name="docs_list" id="docs_list" value="' .  base64_encode(serialize($assigneddocslist)) . '" />';

Then, .. on the form handler side, I am doing the following:

// UNSERIALIZE THE ARRAY
$docs_list = unserialize(base64_decode($_POST['docs_list']));

// LOOP THROUGH FILE UPLOAD FIELDS
foreach ($docs_list as $document_id) {      
      $upload_field_name = 'upload_' . $document_id;
      $tmpName = $_FILES[$upload_field_name]['tmp_name'];
}

This is as far as I've gotten.  More specifically, I've figured out how to recreate the form field names and retrieve their values on the form handler side.  However, ... right now,  I am only able to retrieve the first element within the $_FILES array for each file upload field.  

How can I adapt my code so that if multiple files have been uploaded for a single file upload field, .. I'd be able to retrieve all of the filenames (and perform rename & move operations on each of them) ?   Any help would be appreciated.

Thanks!
- Yvan


Answer : Handling multipe file uploads using PHP (using jquery multi-file upload javascript)

This may take some work to adapt it to jQuery, but I can show you how a simple HTML upload works when you have multiple files from the client.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php


// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt', 'pdf');

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;



// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$errors    = array(
    0 => "Success!",
    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3 => "The uploaded file was only partially uploaded",
    4 => "No file was uploaded",
    6 => "Missing a temporary folder",
    7 => "Cannot write file to disk"
);




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        NOTE THE CHOICE OF ENCTYPE IN THE HTML FORM STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
    -->

    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
    <input type="submit" name="_submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT




else // WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
{

// THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

// ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {

// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

// SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
        $my_file     = $uploads . '/' . $f_name .'.'. $f_type;

// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

// IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

// GET THE FILE SIZE
        $file_size    = number_format($my_uploaded_file["size"]);

// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
        if (!file_exists($my_new_file))
        {
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            else
            {
                $upload_success = -1;
            }

// IF THE FILE ALREADY EXISTS
        }
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            }
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><b>Attempted Backup Failed!</b>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

// REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><b><i>$my_file</i></b> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
// END ITERATOR
    }
}
Random Solutions  
 
programming4us programming4us