p.luck
p.luck

Reputation: 723

Wordpress: PHP multiple file upload

I have a HTML form for a file upload, which sends the uploaded file to the backend directory of my wordpress site. How can I enable multiple file uploads? I tried simply adding multiple="multiple" to my file upload form (which allowed me to select multiple files) but in the directory only one file is uploaded. Here is the form:

<form action="http://www.aerex.co.uk/php-upload/" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple">
    <input type="submit" value="Upload Image" name="submit">
</form>

The PHP for the action page:

<?php
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/';
    $target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"]);
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
         $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
          if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
            } else {
             echo "File is not an image.";
             $uploadOk = 0;
      }
    }
?>

Upvotes: 0

Views: 2674

Answers (1)

You change this

<form action="http://www.aerex.co.uk/php-upload/" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload[]" id="fileToUpload" multiple="multiple">
    <input type="submit" value="Upload Image" name="submit">
</form>

and your php

$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/';
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
  foreach ($_FILES['fileToUpload']['name'] as $f => $name) {     
    if(isset($_POST["submit"])) { 
     $target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"][$f]);
      move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$f], $target_file);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
           $check = getimagesize($target_file);
            if($check !== false) {
              echo "File is an image - " . $check["mime"] . ".";
              $uploadOk = 1;
              } else {
               echo "File is not an image.";
               $uploadOk = 0;
        }
    }

  }
}

Upvotes: 2

Related Questions