Загрузка нескольких изображений через PHP - PullRequest
0 голосов
/ 06 апреля 2020

Я начал изучать PHP, и я делаю сайт. Я пытаюсь добавить изображения в галерею альбома, но с помощью приведенного ниже кода загружает только 1 изображение.

Я пытался понять, в чем проблема, но, похоже, я не выглядел достаточно хорошо, и мне хотелось спросить, как я могу добавить несколько изображений одновременно с кодом ниже?

Что я делаю не так?

<?php

if (isset($_POST['create_image'])) {
  $gallery_album_id = escape($_POST['gallery_album_id']);
  // Access the $_FILES global variable for this specific file being uploaded
  // and create local PHP variables from the $_FILES array of information
  $fileName = $_FILES["uploaded_file"]["name"]; // The file name
  $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
  $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
  $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
  $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
  $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName);
  $kaboom = explode(".", $fileName); // Split file name into an array using the dot
  $fileExt = end($kaboom); // Now target the last array element to get the file extension
  $fileName = time().rand().
  ".".$fileExt;
  // START PHP Image Upload Error Handling --------------------------------------------------
  if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
  } else if ($fileSize > 5242880) { // if file size is larger than 5 Megabytes
    echo "ERROR: Your file was larger than 5 Megabytes in size.";
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    exit();
  } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName)) {
    // This condition is only if you wish to allow uploading of specific file types    
    echo "ERROR: Your image was not .gif, .jpg, or .png.";
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    exit();
  } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
    echo "ERROR: An error occured while processing the file. Try again.";
    exit();
  }
  // END PHP Image Upload Error Handling ----------------------------------------------------
  // Place it into your "uploads" folder mow using the move_uploaded_file() function
  $moveResult = move_uploaded_file($fileTmpLoc, "images_uploads/$fileName");
  // Check to make sure the move result is true before continuing
  if ($moveResult != true) {
    echo "ERROR: File not uploaded. Try again.";
    exit();
  }
  // Display things to the page so you can see what is happening for testing purposes
  echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
  echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
  echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
  echo "The file extension is <strong>$fileExt</strong><br /><br />";
  echo "The Error Message output for this upload is: $fileErrorMsg";
  $query = "INSERT INTO gallery_gallery(gallery_album_id, gallery_images) ";
  $query. = "VALUES('{$gallery_album_id}','{$fileName}') ";
  $create_post_query = mysqli_query($connection, $query);
  confirmQuery($create_post_query);
}
<div class="col-lg-12">
   <div id="image-holder"></div>
</div>
<div class="form-group">
   <div class="custom-file">
      <label for="gallery_image">Insert Images to Album</label>
      <input type="file" id="gallery_album_image" multiple name="uploaded_file" >
   </div>
</div>

Я пытался, но не мог понять. Иногда он не загружал, иногда не получал файл для загрузки.

1 Ответ

1 голос
/ 06 апреля 2020

Попробуйте указать атрибут имени входного имени файла в виде массива:

<input type="file" id="gallery_album_image" multiple name="uploaded_file[]" >

, и тогда вы должны рефакторинг кода работать с $ _FILES. Эти значения будут массивами:

$_FILES["uploaded_file"]["name"][0..num of images]
$_FILES["uploaded_file"]["tmp_name"][0..num of images]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...