I'm trying to upload multiple images to the server at once. I'm using an upload script that works for single images. However upon adding the for loop, the script no longer seems to work.

I've commented out the move_upload_file function for tested purposes and replaced them with echo statements.

Upon trying to upload multiple files I get the error handler: "You can't upload files of this type!". And after adding some echo statements for the file name and extensions, it displays either as "Sis" or 000.

Any suggestions on how to fix this issue would be greatly appreciated. My PHP code is shown below:

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_POST['submit'])) {
  $total = count($_FILES['file']['name']);

  for( $i=0 ; $i < $total ; $i++ ) {
  $file = $_FILES['file'];

  $fileName = $_FILES['file']['name'][$i];
  $fileTmpName = $_FILES['file']['tmp_name'][$i];
  $fileSize = $_FILES['file']['size'][$i];
  $fileError = $_FILES['file']['error'][$i];
  $fileType = $_FILES['file']['type'][$i];

  $fileExt = explode('.', $fileName);
  $fileActualExt = strtolower(end($fileExt));
  // File types allowed
  $allowed = array('jpg', 'jpeg', 'png', 'gif');
  if (in_array($fileActualExt, $allowed)) {
    if ($fileError === 0) {
      if ($fileSize < 9000000) {
        $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'images/Showroom-images/'.$fileName;
        /*move_uploaded_file($fileTmpName, $fileDestination);
        echo "Success!";*/
        echo $fileName;
        echo $fileDestination;
      } else {
        echo "Your file is too big!";
      }
    } else {
      echo "There was an error, please try again";
    }
  } else {
    echo $fileName + "<br>";
    echo $fileType + "<br>";
    echo $fileActualExt + "<br>";
    echo "You can't upload files of this type!";
  }
}}

?>

Here's the HTML form as well:

<form action="test.php" method="post" enctype="multipart/form-data">
    <input name="file" id="file" type="file" multiple="multiple" />
    <input type="submit" value="submit" id="submit"/>
  </form>

1 Answers

0
Levi Cole On Best Solutions

Ok so I haven't tested your PHP process but from looking at your code you should be able to fix your issue by changing the field name from file to file[] see below.

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

Adding the square brackets basically treats the field as an array which will accept multiple files.

You're also using + to combine strings in your PHP, these should be . instead...

    echo $fileName . "<br>";
    echo $fileType . "<br>";
    echo $fileActualExt . "<br>";
    echo "You can't upload files of this type!";