0

I am trying to upload multiple images on my website when user clicks on upload button. I was able to do that for one image, but I am not sure how to do for multiple images.

My code:

index.php

<html>
<head></head>
<body>
    <form action="backend.php" method="POST" enctype="multipart/form-data">
      <input type="file" name="file" >
      <button type="submit" name="submit">button</button>
    </form>
</body>

</html>

database.php

<?php
   if (isset($_POST['submit'])) {
    $file = $_FILES['file'];

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

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));
    $allowed = array('jpg', 'jpeg', 'png', 'pdf');
    if (in_array($fileActualExt, $allowed)) {
        if($fileError === 0) {
            if ($fileSize < 10000000) {
                  $fileNameNew = uniqid('', true).".".$fileActualExt;
                  $fileDestination = 'uploads/'.$fileNameNew;
                  move_uploaded_file($fileTmpName, $fileDestination);
                  header("Location: index.php?uploadsuccess");
            } else {
                echo "Your file is too big!";
            }
        } else {
            echo "There was an error uploading your file";
        }
       
    } else {
        echo "You cannot upload files of this type!";
    }
}

?>

I changed a bit in my code (index.html) so I can at least select multiple images: <input type="file" name="file[]" multiple> but when I do that and click on upload it says:

Warning: explode() expects parameter 2 to be string, array given in /opt/lampp/htdocs/testing/backend.php on line 11

Warning: end() expects parameter 1 to be array, null given in /opt/lampp/htdocs/testing/backend.php on line 12 You cannot upload files of this type!

I assume cause it expects it to be string but I have an array now. How can I make my code work in database.php for multiple files? It works for single image, but not for multiple. If someone can reckon something?

3

1 Answer 1

1

Ok, let's say you have this HTML:

<form action="backend.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple />
    <button type="submit" name="submit">button</button>
</form>

Normally (without multiple and with name="file"), your PHP would receive something like this:

$_FILES['file']['name'] // contains the file name

However, sending multiple files, your PHP will receive these files as following:

$_FILES['file']['name'][0] // contains the first file name
$_FILES['file']['name'][1] // contains the second file name
// ...

Read more.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.