Home > database >  Uploading multipile files using HTML file input
Uploading multipile files using HTML file input

Time:01-31

i'm trying to upload a bunch of files using file type input with php i tried so far to make upload only one file and it worked the problem is that when i added [] to the name attribute it started to print Uploaded data error.

HTML

<form id="theform" action="upload.php" onsubmit="event.preventDefault(); return myFunction2();" method="post" enctype="multipart/form-data">
    <input id="file" name="uploadedFile[]" onchange="uptoserver();" style="display:none;"type="file" multiple>
    <div >
        <div id="buttons" style="display:none !important;">
            <button type="submit"   style="font-family:Hana; font-size:18px; border:1px solid black !important;">
                <img src="style\image\add.png" width="32" />&nbsp;تكوين كشف&nbsp;
            </button>&nbsp;
            <button type="button"  style="font-family:Hana; font-size:18px; border:1px solid black !important;">
                <img src="style\image\camera.png" width="32" />&nbsp;إضافة نموذج&nbsp;
            </button>&nbsp;
        </div>
    </div>
</form>

Javacript :

function myFunction2(){
    document.getElementById('file').click();
    console.log('reading form');
}

function uptoserver(){
    // var formscounter = parseInt(document.getElementById("counter").value);
    if(!document.getElementById("file").files.length == 0) {
        const form = document.getElementById('theform');
        form.submit();
        console.log('fucking working');
    }
}

upload.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "Empty data, please select file";
    die;
}

if (!isset($_FILES["uploadedFile"])) {
    echo "Wrong data struct";
    die;
}

if ($_FILES["uploadedFile"]['error'] != 0) {
    echo "Uploaded data error";
    die;
}
$target_dir    = "uploads/";
$target_file   = $target_dir . basename($_FILES["uploadedFile"]["name"]);
$allowUpload   = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize   = 80000000;
$allowtypes    = array('jpg', 'png', 'jpeg', 'gif');

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["uploadedFile"]["tmp_name"]);
    if($check !== false) {
        //
    } else {
        echo "This's not image file.";
        $allowUpload = false;
    }
}

if (file_exists($target_file)) {
    require "other\\fileExsist.php";
    $allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"] > $maxfilesize) {
    require "other\\fileSize.php";
    $allowUpload = false;
}

if (!in_array($imageFileType,$allowtypes )) {
    require "other\\fileExtenstion.php";
    $allowUpload = false;
}

if ($allowUpload) {
    if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
        //   echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
        //   echo $target_file;
        require "prepare.php";
        echo count($_FILES["uploadedFile"]);
    } else {
        echo "Error when upload file.";
    }
    // $total = count($_FILES['uploadedFile']['name']);

// // Loop through each file
// for( $i=0 ; $i < $total ; $i   ) {

//   //Get the temp file path
//   $tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];

//   //Make sure we have a file path
//   if ($tmpFilePath != ""){
//     //Setup our new file path
//     $newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];

//     //Upload the file into the temp dir
//     if(move_uploaded_file($tmpFilePath, $newFilePath)) {

//       //Handle other code here

//     }
//   }
// }
} else {
    echo "";
}
?>

CodePudding user response:

Your original structure works perfectly fine because, when you're uploading a single file, line 18 is if ($_FILES["uploadedFile"]['error'] != 0), and this returns 0.

When you send through an array of files, even if a single file is sent, the uploadFile array is now an array of arrays, as below.

[_FILES] => Array
    (
        [uploadedFile] => Array
            (
                [name] => Array
                    (
                        [0] => funnyMusclePose.jpg
                    )

                [type] => Array
                    (
                        [0] => image/jpeg
                    )

                [tmp_name] => Array
                    (
                        [0] => C:\Development\wamp64\tmp\phpE949.tmp
                    )

                [error] => Array
                    (
                        [0] => 0
                    )

                [size] => Array
                    (
                        [0] => 735092
                    )

            )

    )

This means $_FILES["uploadedFile"]['error'] will always evaluate to true because it doesn't equal 0.

From here on out, you can wrap this entire function in a for() loop and iterate over each of the internal array items to get the data you're after, ie.

for($i = 0; $i < count($_FILES["uploadedFile"]["name"]); $i  ) {
  if ($_FILES["uploadedFile"]['error'][$i] != 0)
  {
    echo "Uploaded data error";
    die;
  }
  $target_dir    = "uploads/";
  $target_file   = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
  $allowUpload   = true;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  $maxfilesize   = 80000000;
  $allowtypes    = array('jpg', 'png', 'jpeg', 'gif');

  if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["uploadedFile"]["tmp_name"][$i]);
      if($check !== false)
      {
          //
      }
      else
      {
          echo "This's not image file.";
          $allowUpload = false;
      }
  }

  if (file_exists($target_file))
  {
      require "other\\fileExsist.php";
      $allowUpload = false;
  }
  if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
  {
      require "other\\fileSize.php";
      $allowUpload = false;
  }

  if (!in_array($imageFileType,$allowtypes ))
  {
      require "other\\fileExtenstion.php";
      $allowUpload = false;
  }
  
  // Add the rest of the code here
}
  • Related