Search code examples
phphtmlmultiple-file-upload

Upload multiple image files in PHP


I am currently trying to upload multiple image files but I have some errors encountered as below:

Notice: Undefined index: productPic in D:\laragon\www\byte\add_product.php on line 25

Notice: Trying to access array offset on value of type null in D:\laragon\www\byte\add_product.php on line 25

Warning: count(): Parameter must be an array or an object that implements Countable in D:\laragon\www\byte\add_product.php on line 25

Below is the PHP code starting from line 25 to line 40:

$totalFile = count($_FILES['productPic']['name']);   //line 25
 
for($i=0; $i<$totalFile; $i++)
{
  //ensure the file path is exist
  if($_FILES['productPic']['tmp_name'][$i] != "")
  {
    // upload the file into the temp directory
    if(move_uploaded_file($_FILES['productPic']['tmp_name'][$i],$_FILES['productPic']['name'][$i]))
    {
      $upload = 1;
      $pic[$i] == $_FILES['productPic']['name'][$i];
    }
  }
}

Below is the partial HTML code:

<form class="w-100" name="addProductForm" method="POST" action="add_product.php">
    .
    .
    <div class="row">
        <div class="col form-group">
            <input type="file" class="form-control py-1" name="productPic[]" accept="image/*" multiple required>
        </div>
    </div>
    .
    .
</form>

Solution

  • You have two problems in your code

    (A) make sure you have enctype='multipart/form-data' in the form tag

    So the HTML should be like:

    <form class="w-100" name="addProductForm" method="POST" enctype='multipart/form-data' action="add_product.php">
        <div class="row">
            <div class="col form-group">
                <input type="file" class="form-control py-1" name="productPic[]" accept="image/*" multiple required>
            </div>
        </div>
    <input type=submit>
    </form>
    

    (B) The following line in your PHP is incorrect (you need a assignment operator, not a comparison operator):

    $pic[$i] == $_FILES['productPic']['name'][$i];
    

    should be

    $pic[$i] = $_FILES['productPic']['name'][$i];
    

    So the PHP should be like:

    <?php
    ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
    
    $totalFile = count($_FILES['productPic']['name']);
    
    for($i=0; $i<$totalFile; $i++) {
                // ensure the file path is exist
                if($_FILES['productPic']['tmp_name'][$i] != "") {
                   if (move_uploaded_file($_FILES['productPic']['tmp_name'][$i],$_FILES['productPic']['name'][$i])){
                        $upload = 1;
                        $pic[$i] = $_FILES['productPic']['name'][$i];
                    }
                }
    }
    
    var_dump($pic);
    ?>
    

    Last but not least, make sure that the directory is writable, otherwise the upload will fail