【问题标题】:How to upload multiple files from HTML form, using PHP "SWITCH" function with more than one input file?如何使用带有多个输入文件的 PHP“SWITCH”功能从 HTML 表单上传多个文件?
【发布时间】:2019-03-24 10:33:03
【问题描述】:

[LAST EDIT] 最后一个代码出现一些问题后,这里是一个干净的代码。希望可以帮助某人。

// -- HTML --

//-- 在输入文件中使用 name="image[]" 不起作用。 //-- 如果使用 name="image1"、name="image2"、name="image3" 等会更好。

<div class="container">

  <label for="title">Title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image1" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image2" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image3" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image4" id="upload_file_pc" required><br /><br />

</div>

  <button type="submit" name="form_upload_file" class="btn btn-primary">Envoyer</button>

// -- PHP --

foreach($_FILES as $file){

            $filesname = ($file["name"]); //-- Client file name

            $target_dir = "upload/"; //-- Here you can add after the " /" something for recognize the file up.

            $target_file = $target_dir . basename($filesname);

            $filestmp = ($file["tmp_name"]);

            $filessize = ($file["size"]);

            $uploadOk = 1;

            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

        // Check if the image file is an actual image or fake image

            if(isset($_POST["submit"])){

                $check = getimagesize($filessize);

                if($check !== false) {

                    $messagemerci = "File is an image - " . $check["mime"] . ".";

                    $uploadOk = 1;

                } 

                else {

                    $messagemerci = "File is not an image.";

                    $uploadOk = 0;

                }
            }

        // Check if the file already exists

            if (file_exists($target_file)) {

                $messagemerci = "Sorry, file already exists.";

                $uploadOk = 0;
            }

        // Check file size

            if ($filessize > 500000) {

                $messagemerci = "Sorry, your file is too large.";

                $uploadOk = 0;

            }

        // Allow certain file formats

            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" ) {

                $messagemerci = "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.";

                $uploadOk = 0;
            }

        // Check if $uploadOk is set to 0 by an error

            if ($uploadOk == 0) {

                $messagemerci = "Sorry, your file was not uploaded.";

        // if everything is ok, try to upload the file

            } 

            else {

                if (move_uploaded_file($filestmp, $target_file)) {

                    $messagemerci = "The file ". basename( $filesname). " has been uploaded.";

                } 

                else {

                    $messagemerci = "Sorry, there was an error uploading your file.";

                }
            }
        };                  

现在我会在里面做一些安全过程,它不会那么糟糕。

感谢您的宝贵时间。

BK201

// -- 开始 --

我不明白如何使用 PHP 从 HTML 表单下载多个文件。

我不想用这个:&lt;input type="file" name="" multiple&gt;

一个输入允许多个文件,我暂时不想使用它。

让我们开始吧:

我可以使用此代码上传一个文件:

    <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload the file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

但是我怎样才能上传多个文件呢?

我认为我需要:

foreach ($_FILES["image”]["tmp_name"] as $index){

//--something

}

但是什么都没有……

我从 Okonomiyaki3000 here(顺便说一句,有了你的回答我看到了希望 :)...)看到了这个答案

$files = array_map('RemapFilesArray'
    (array) $_FILES['attachments']['name'],
    (array) $_FILES['attachments']['type'],
    (array) $_FILES['attachments']['tmp_name'],
    (array) $_FILES['attachments']['error'],
    (array) $_FILES['attachments']['size']
);

function RemapFilesArray($name, $type, $tmp_name, $error, $size)
{
    return array(
        'name' => $name,
        'type' => $type,
        'tmp_name' => $tmp_name,
        'error' => $error,
        'size' => $size,
    );
}

我了解流程,但对我不起作用...

我尝试了所有方法,但我不明白如何循环每个 $_files[POST]

也许我犯了一个我看不到的错误,因为我是新手。

我也检查了其他解决方案,最后,我来这里是因为你的声誉。

所以这里是我在询问之前尝试过的完整示例。

//-- In this case, I want to upload multiple files with an HTML form and a PHP action.
//-- I don't understand how to loop with each file in $_Files.
//-- I made 3 examples, working for 1 file upload but not for 4 files.
//-- Anyone can explain to me how it works. NOT JUST WRITING THE RIGHT WAY PLEASE.



<html>
<body>

<h4>Documents justificatifs:</h4>

  <form action="upload_file_pc.php" name="upload_file_pc" method="post" enctype="multipart/form-data">

    <div class="container">

      <label for="title">Title:</label>
      <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
      <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

      <label for="title">title:</label>
      <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
      <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

      <label for="title">title:</label>
      <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
      <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

      <label for="title">title:</label>
      <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
      <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

    </div>

      <button type="submit" name="form_upload_file" class="btn btn-primary">Envoyer</button>

   </form>

 </body>
 </html>

 //-- Exemple 1:

 <?php

 function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}



if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['image']);

    foreach ($file_ary as $file) {
        print 'File Name: ' . $file['name'];
        print 'File Type: ' . $file['type'];
        print 'File Size: ' . $file['size'];
    }
}


 ?>

 //-- Exemple 2:

 <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload the file
} else {
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

//-- Exemple 3:

<?php

  // Settings
  $allowedExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
  $maxSize = 2097152;
  $storageDir = 'a/b/c/tmp_images';

  // Result arrays
  $errors = $output = array();

  if (!empty($_FILES['image'])){  

    // Validation loop (I prefer for loops for this specific task)
    for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

      $fileName = $_FILES['image']['name'][$i];
      $fileSize = $_FILES['image']['size'][$i];
      $fileErr = $_FILES['image']['error'][$i];
      $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

      // Validate extension
      if (!in_array($fileExt, $allowedExtensions)) {
        $errors[$fileName][] = "Format $fileExt in image $fileName is not accepted";
      }

      // Validate size
      if ($fileSize > $maxSize) {
        $errors[$fileName][] = "$fileName excedes the maximum file size of $maxSize bytes";
      }

      // Check errors
      if ($fileErr) {
        $errors[$fileName][] = "$fileName uploaded with error code $fileErr";
      }

    }

    // Handle validation errors here
    if (count($errors) > 0) {
      die("Errors validating uploads: ".print_r($errors, TRUE));
    }

    // Create the storage directory if it doesn't exist
    if (!is_dir($storageDir)) {
      if (!mkdir($storageDir, 0755, TRUE)) { // Passing TRUE as the third argument creates recursively
        die("Unable to create storage directory $storageDir");
      }
    }

    // File move loop
    for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

      // Get base info
      $fileBase = basename($_FILES['image']['name'][$i]);
      $fileName = pathinfo($fileBase, PATHINFO_FILENAME);
      $fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
      $fileTmp = $_FILES['image']['tmp_name'][$i];

      // Construct destination path
      $fileDst = $storageDir.'/'.basename($_FILES['image']['name'][$i]);
      for ($j = 0; file_exists($fileDst); $j++) {
        $fileDst = "$storageDir/$fileName-$j.$fileExt";
      }

      // Move the file    
      if (move_uploaded_file($fileTmp, $fileDst)) {
        $output[$fileBase] = "Stored $fileBase OK";
      } else {
        $output[$fileBase] = "Failure while uploading $fileBase!";
        $errors[$fileBase][] = "Failure: Can't move uploaded file $fileBase!";
      }

    }

    // Handle file move errors here
    if (count($errors) > 0) {
      die("Errors moving uploaded files: ".print_r($errors, TRUE));
    }

  }


  ?>

[编辑] 感谢 NiMusco 的帮助。现在我更好地理解了如何查看 $_FILES 中上传的内容,但是当我将 $_FILES['name'] 放入 "$data" 并回显 "$data" 时,我得到 "Array"...

所以我尝试了一些简单的方法,也许我做错了,但对我来说这是有效的,但我没有得到我期望的结果。

这里:

 ?php
    if(!empty($_FILES))
    {
      foreach($_FILES as $file)
      {
        $namefile = $file['name'];
        echo $namefile;
      }
    }
    ?>". 


But what I get is " Array ".... not the file name. here what I get when I do:

print_r($_FILES) :" Array
    (
        [image] => Array
            (
                [name] => Array
                    (
                        [0] => img_1.jpg
                        [1] => img_2.jpg
                        [2] => img_3.jpg
                        [3] => img_4.jpg
                    )

                [type] => Array
                    (
                        [0] => image/jpeg
                        [1] => image/jpeg
                        [2] => image/jpeg
                        [3] => image/jpeg
                    )" etc...."

我认为“Array”指的是:“[name] => Array” of print_r ...

也许我需要从头开始学习 PHP。我肯定错过了一些东西。

[编辑] 我在 NiMusco 的帮助下找到了解决方案。

所以这里是我为我工作的完整代码:

// -- HTML --

<div class="container">

  <label for="title">Title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

  <label for="title">title:</label>
  <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  <input type="file" class="form-control" name="image[]" id="upload_file_pc" required><br /><br />

</div>

  <button type="submit" name="form_upload_file" class="btn btn-primary">Envoyer</button>

// -- PHP --

foreach($_FILES as $file){

            $filesname = ($file["name"]);

            $target_dir = "upload/";

            $target_file = $target_dir . basename($filesname);

            $filestmp = ($file["tmp_name"]);

            $filessize = ($file["size"]);

            $uploadOk = 1;

            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

        // Check if the image file is an actual image or fake image

            if(isset($_POST["submit"])){

                $check = getimagesize($filessize);

                if($check !== false) {

                    $messagemerci = "File is an image - " . $check["mime"] . ".";

                    $uploadOk = 1;

                } 

                else {

                    $messagemerci = "File is not an image.";

                    $uploadOk = 0;

                }
            }

        // Check if the file already exists

            if (file_exists($target_file)) {

                $messagemerci = "Sorry, file already exists.";

                $uploadOk = 0;
            }

        // Check file size

            if ($filessize > 500000) {

                $messagemerci = "Sorry, your file is too large.";

                $uploadOk = 0;

            }

        // Allow certain file formats

            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" ) {

                $messagemerci = "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.";

                $uploadOk = 0;
            }

        // Check if $uploadOk is set to 0 by an error

            if ($uploadOk == 0) {

                $messagemerci = "Sorry, your file was not uploaded.";

        // if everything is ok, try to upload the file

            } 

            else {

                if (move_uploaded_file($filestmp, $target_file)) {

                    $messagemerci = "The file ". basename( $filesname). " has been uploaded.";

                } 

                else {

                    $messagemerci = "Sorry, there was an error uploading your file.";

                }
            }
        };                  

感谢您的宝贵时间。

BK201

【问题讨论】:

  • 在输入文件标签中使用多个属性

标签: php file-upload forms http-post


【解决方案1】:

使用:

<input type="file" name="images[]" multiple>

【讨论】:

  • 您好 Waseel,感谢您回答我。就因为这个??我认为“多个”是用于在一个输入类型 = 文件中上传多个文件...好吧,我尝试回到这里。
  • 是的,很可能。如果要上传多张图片,则必须在输入中使用多个属性,它将发送一组图片。您可以从以下链接中看到:you can see this question answer希望对您有所帮助。
  • 好的。我明白你的意思,但我不想通过使用一个输入类型=“文件”多个来解决问题。也许以后我会用这个,谢谢你。但是目前,这个问题在我的脑海中,所以我想了解它是如何工作的,然后我会看看哪一个适合我的项目。我想学习并找到解决方案。我不想找到刚刚出现的解决方案。我想看看里面,尝试等等。对不起,这不是一个“心情不好的答案”,这只是对我所期望的澄清。谢谢Waseel!
【解决方案2】:

您是否尝试打印 $_FILES 的内容?它会为你澄清事情。

无论您有多少输入文件,或者您如何命名它。 只需迭代 $_FILES。

if(!empty($_FILES))
{
  foreach($_FILES as $file)
  {
    $name = $file['name'];
    $folder = "/uploads";

    move_uploaded_file($name, $folder . "/" . $name);
  }
}

根据 OP 需要添加了一个完整的 HTML/PHP 示例。

<form method="post" enctype="multipart/form-data">
  <input type="file" name="file1">
  <input type="file" name="file2">
  <input type="file" name="file3">
  <input type="submit">
</form>

<?php

  if(!empty($_FILES))
  {
    foreach($_FILES as $file)
    {
      $name = basename($file['name']);
      $folder = "/uploads";

      move_uploaded_file($name, $folder . "/" . $name);
    }
  }

?>

在这种情况下,$_FILES 会为您提供类似这样的结构:

Array
(
    [file1] => Array
        (
            [name] => IMG_20180918_094315304.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpYDmeY7
            [error] => 0
            [size] => 5342893
        )

    [file2] => Array
        (
            [name] => IMG_20180918_094323718.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php9cXCkE
            [error] => 0
            [size] => 5783548
        )

    [file3] => Array
        (
            [name] => IMG_20180918_094336974.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phphljHJa
            [error] => 0
            [size] => 4819618
        )

)

【讨论】:

  • 谢谢NiMusco,我没有用这个方法。我从来没有用过,所以是时候了。比你!
  • 不客气。做 print_r($_FILES) 你会看到的。我想你可以从那里开始。
  • 好的。我做到了,我在数组中看到了所有文件。所以现在我必须按它们的名称在这些数组中循环,如下所示:“ foreach ($_FILES['image']['name'] as ??) { my code; }" ?
  • 好的。谢谢您的回答。我尝试了一些东西,然后我回来了。我觉得这个问题的退出。
  • 所以我尝试了一些简单的方法,也许我做错了,但对我来说它是有效的,但我没有得到我期望的结果。这里:“?php if(!empty($_FILES)) { foreach($_FILES as $file) { $namefile = $file['name']; echo $namefile; } } ?>”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多