Hey guys! Welcome back to the new tutorial of Tutoid “Multiple File Uploads To Server With PHP”  . Today I will show you how to upload multiple files to the server. In the previous tutorial of PHP File Upload I showed you how to upload a single file.

Basics:

  1. Here we add attribute “multiple” in input type file so that we can choose multiple files.
  2. We add two brackets “[]” after the file attribute ‘name’ so that an indexed array could be created.

So finally it would look something like this.

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

How it works?

Well using for loop we cycle through the indexed array, we just need to execute the command ‘move_uploaded_file()’ with different filename. So if output the array it would look something like this.

Array ( [file] =>
Array ( [name] => Array ( [0] => 13904918840_913dc2d5c0_k_www.flickr.com_groups_freeuse.jpg [1] => 14089476933_1faca5d148_h_www.flickr.com_groups_freeuse.jpg [2] => 14274234397_1cf6c042b4_k_www.flickr.com_groups_freeuse.jpg [3] => 14444162699_db70048443_k_www.flickr.com_groups_freeuse.jpg ) [type] => Array ( [0] => image/jpeg [1] => image/jpeg [2] => image/jpeg [3] => image/jpeg ) [tmp_name] => Array ( [0] => F:xampptmpphpBF23.tmp [1] => F:xampptmpphpC4A3.tmp [2] => F:xampptmpphpC715.tmp [3] => F:xampptmpphpC735.tmp ) [error] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 ) [size] => Array ( [0] => 1152189 [1] => 711084 [2] => 1207521 [3] => 1548724 ) ) ) Upload Files

So here are my files.

style.css

* {font-family: Consolas;}
    form {
        width: 300px;
        padding: 20px;
        background: white;
        margin: 200px auto;
        border-radius:10px;
        color: #727272;
    }
    form input {
        width: 100%;
        padding:5px;
        font-size:20px;
        margin-bottom: 10px;
    }
    form input[type="submit"] {
        color: white;
        background: #ff4081;
        border:0;
        border-radius: 10px;

    }
    body {
        background: #303f9f;

    }

Form

<body>
<form method="POST" enctype="multipart/form-data">
<h1>Upload Files</h1>
<input type="file" name="file[]" multiple required>
 <input type="submit" value="Upload!">
</form>
</body>

PHP Script

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_FILES['file']['name'])){
 $folder = 'uploads/';
 $threshold = count($_FILES['file']['name']);
 for($i = 0; $i<$threshold; $i++){
 $filename = $_FILES['file']['name'][$i];
 $path = $folder.$filename;
 if(strpos($filename,'.php') == true){
 echo "Choose another FIle!";
 }
 elseif (strpos($filename,'.exe') == true){
 echo "Choose another FIle!";
 }
 else {
 if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$path)){
 echo "File ".$i.' Uploaded Success!
';
 }
 else {
 echo "File $i Upload Failed! :/";
 };
 };
 };
};
?>

Well now you are ready with your application that uploads multiple files to the server very easily.

Download Sample Project.

Watch Video Tutorial On Tutoid.

 

Advertisements