Multi file upload using php

Hi all

I had success uploading a file to the server, I’m trying to upload multiple files but no success since I’m not to familiar with the for loop syntax on php.

This is what I have so far:

php 1:

<form method="post" action="get_moola_upload.php" enctype="multipart/form-data">

<input type="file" name="myfile" name="myfile[]" multiple> 
<input class="btn" type="submit" name="upldocsbtn" value="Upload Documents"></input><br><br>

...

php2:

if (isset($_POST['upldocsbtn']) )
{
 $countfiles = count($_FILES['myfile']['name']);
 for($i=0;$i<$countfiles;$i++)
 {
    $file = $_FILES['myfile']; 
    $fileName = $_FILES['myfile']['name'];
    $fileTmpName = $_FILES['myfile']['tmp_name'];  //location
    $fileSize = $_FILES['myfile']['size'];
    $fileError = $_FILES['myfile']['error'];
    $fileType = $_FILES['myfile']['type'];
    $fileExtTmp = explode('.',$fileName);
    $fileExt = strtolower(end($fileExtTmp)); 
    $allowed = array('pdf','bmp','gif','jpeg','jpg');

    if (in_array($fileExt,$allowed))
    {
        if ($fileError === 0)
        {
            $fileNameNew = "C".$_POST['cnumber']."_".uniqid('',true).".".$fileExt;
            $fileDestination = 'deals/'.$fileNameNew;
            move_uploaded_file($fileTmpName,$fileDestination);
        }
        else
        {
            echo "<script type='text/javascript'>alert('Error uploading file!')</script>";
        }
    }
    else 
    {
        echo "<script type='text/javascript'>alert('You cannot upload files of this file type!')</script>";
   }
 }
}

Well, just use the “multiple” option for the file inputs and parse thru them… Here is a simple example:

<form method='post' action='' enctype='multipart/form-data'>
 
 <input type="file" name="file[]" id="file" multiple>
 <input type='submit' name='submit' value='Upload'>

</form>

Simple enough… Now the code…

<?php 
if(isset($_POST['submit'])){
 // Count total files
 $countfiles = count($_FILES['file']['name']);
 
 // Looping all files
 for($i=0;$i<$countfiles;$i++){
   $filename = $_FILES['file']['name'][$i];
   
   // Upload file
   move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
    
 }
} 
?>

In case you do not see the difference, there is no such thing as < /input > ! ! !

Sponsor our Newsletter | Privacy Policy | Terms of Service