As discussed in earlier post How to upload Files in PHP. This post is all about Uploading Multiple Files with PHP using ‘For Loop’.

Well the process is same as simple file upload, but in this we create an array(indexed array starting from 0) of files that are selected to upload and we cycle through them using for loop. Pretty simple.. right!

So to enable multiple file uploads we need to add an attribute “multiple” to our input type=”file” and we need to change the name attribute to ‘file[]’ to create an array, rest is same in the form.


<input type="file" name="file[]" multiple>

So Here’s how your form would look.


<pre>
<form method="POST" enctype="multipart/form-data">

<h1>Upload File</h1>

    <input type="file" name="file[]" multiple>
    
    <input type="submit">
</form>
</pre>

And the style.css is same in the previous post.So now here comes the PHP script.


<pre>if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_FILES['file']['name'])){
        $x = 0;
        $threshold = count($_FILES['file']['name']);
        echo $threshold;
        for($x = 0; $x < $threshold; $x++){
            $filename = $_FILES['file']['name'][$x];
            if(strpos($filename,'.php') == true) // If file is a php
            {
                continue;
            }
            else{
                $dir='uploads/'.$filename;
                if(file_exists($dir) == true) // To check if the file exist
                {
                    $filename = uniqid().$filename; //if file exist..we rename so that it cannot replace existing file.
                };
                move_uploaded_file($_FILES['file']['tmp_name'][$x],'uploads/'.$filename);

            };
        };
        header('location:index.php?msg=2');
    };
if(isset($_GET['msg']) && !empty($_GET['msg'])){
    if($_GET['msg'] == 1){
        echo "
<div id='message' style='background: red'>Upload Failed!! </div>

";
    };
    if($_GET['msg'] == 2){
        echo "
<div id='message' > Uploaded Sucessfully!! </div>

";

    };
};</pre>

So now in this..what we did here is count the numbers of files that are to be uploaded through count($string)
and we set a variable $x= 0 as indexed array starts with 0. Each file properties(name,size,type etc) can be accessed through

$_FILES['file']['name'][$x]

so we started a for loop and simply uploaded the files, and in this we have

if(strpos($filename,'.php') == true) // If file is a php
            {
                continue;
            }

to skip the file and continue with another file if the current file is a .php file.

You can have a Sample Project here.