23

I've been trying to make this work for quite some time now. But I can't seem to make it work. I wanted to have a multiple image upload form with only using one input.

this is my upload.php

<?php
include("../include/session.php");

session_start();
$allowedExts = array("jpeg", "jpg", "png", "gif");
$extension = end(explode(".", $_FILES["upload"]["name"]));

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

        if (($_FILES["upload"]["name"] < 90000000000000000)
            && in_array($extension, $allowedExts)) {
                if ($_FILES["upload"]["error"] > 0)
                {
                    header('location: '.$error); die;
                }
                else
                {

                    if (file_exists("../icons/".$_SESSION["username"] ."/" . $_FILES["upload"]["name"]))
                    {
                    echo "error";
                    }
                    else
                    {
                        if(!is_dir("../icons/". $_SESSION["username"] ."/")) {
                            mkdir("../icons/". $_SESSION["username"] ."/");
                        }

                        $temp = explode(".",$_FILES["upload"]["name"]);
                        $file = rand(1,999999999999) . '.' .end($temp);

                        move_uploaded_file($_FILES["upload"]["tmp_name"], "../icons/". $_SESSION["username"] ."/". $file);  
                    }
                }
            }
        } else {
            echo "yep error";
        }
    }
} 
?>

if i take out the lines

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

With the corresponding closing bracket, it seems to work fine. The image is uploaded perfectly. But the thing is, it only allows me to upload one.

Please I really need your expertise. THank you

2

8 Answers 8

53
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
    $file_name=$_FILES["files"]["name"][$key];
    $file_tmp=$_FILES["files"]["tmp_name"][$key];
    $ext=pathinfo($file_name,PATHINFO_EXTENSION);

    if(in_array($ext,$extension)) {
        if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
        }
        else {
            $filename=basename($file_name,$ext);
            $newFileName=$filename.time().".".$ext;
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
        }
    }
    else {
        array_push($error,"$file_name, ");
    }
}

and you must check your HTML code

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
    <table width="100%">
        <tr>
            <td>Select Photo (one or multiple):</td>
            <td><input type="file" name="files[]" multiple/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
        </tr>
    </table>
</form>

Nice link on:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

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

10 Comments

and how to save these images to database?
@AsifMehmood It's really not a nice idea to save an image as a blob file to the database, except you're working on a small and none SEO seeking project.
@AsifMehmood please take a look here: javascripthive.info/php/…
Why use extract($_POST); ? I remove it and the codes work well. And extract on $_POST seems is poor coding practices. You could find the warning "Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.)" in the php.net manual php.net/manual/en/function.extract.php
@PreciousTom SO whats the alternative for not saving the images to database?
|
2

Multiple Image upload using php full source code and preview available at the below Link.
Sample code:

if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image 

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path.md5(uniqid()).
        ".".$ext[count($ext) - 1]; //set the target path with a new name of image
        $j = $j + 1; //increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
            && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
                echo $j.
                ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else { //if file was not moved.
                echo $j.
                ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else { //if file size and file type was incorrect.
            echo $j.
            ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}

http://www.allinworld99.blogspot.com/2015/05/php-multiple-file-upload.html

1 Comment

Id just like to add to this, the initial $target_path variable needs to be inside the for loop, otherwise the file names that are hashed via md5 are concatenated. Additionally, i removed the hashed file name method as it wasnt right for my needs.
1
<?php
if(isset($_POST['btnSave'])){
    $j = 0; //Variable for indexing uploaded image 

    $file_name_all="";

    $target_path = "uploads/"; //Declaring Path for uploaded images

    //loop to get individual element from the array
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable
        $basename=basename($_FILES['file']['name'][$i]);
        //echo"hi its base name".$basename;
        $target_path = $target_path .$basename;//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < (1024*1024)) //Approx. 100kb files can be uploaded.
        && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
                /***********************************************/

                $file_name_all.=$target_path."*";  
                $filepath = rtrim($file_name_all, '*');  
                //echo"<img src=".$filepath."   >";          

                /*************************************************/
            } else {//if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
    $qry="INSERT INTO `eb_re_about_us`(`er_abt_us_id`, `er_cli_id`, `er_cli_abt_info`, `er_cli_abt_img`) VALUES (NULL,'$b1','$b5','$filepath')";


    $res = mysql_query($qry,$conn); 
    if($res)
        echo "<br/><br/>Client contact Person Information Details Saved successfully";
        //header("location: nextaddclient.php");
        //exit();
    else
        echo "<br/><br/>Client contact Person Information Details not saved successfully";

}
?>

Here $file_name_all And $filepath get 1 uplode file name 2 time?

1 Comment

Is this an answer to the question? If so, please state clearly in how far it solves the question. If this is a question in itself, delete it here and ask a new question.
0

PHP Code

<?php
error_reporting(0);
session_start();
include('config.php');
//define session id
$session_id='1'; 
define ("MAX_SIZE","9000"); 
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//set the image extentions
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{

    $uploaddir = "uploads/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;
           echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
           {
           $time=time();
               //insert in database
           mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
            }

           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit!</span>';

           }

          }
          else
         { 
             echo '<span class="imgList">Unknown extension!</span>';

         }

     }
}

?>

Jquery Code

<script>
 $(document).ready(function() { 

            $('#photoimg').die('click').live('change', function()            { 

                $("#imageform").ajaxForm({target: '#preview', 
                     beforeSubmit:function(){ 

                    console.log('ttest');
                    $("#imageloadstatus").show();
                     $("#imageloadbutton").hide();
                     }, 
                    success:function(){ 
                    console.log('test');
                     $("#imageloadstatus").hide();
                     $("#imageloadbutton").show();
                    }, 
                    error:function(){ 
                    console.log('xtest');
                     $("#imageloadstatus").hide();
                    $("#imageloadbutton").show();
                    } }).submit();


            });
        }); 
</script>

Comments

0
$total = count($_FILES['txt_gallery']['name']);
            $filename_arr = [];
            $filename_arr1 = [];
            for( $i=0 ; $i < $total ; $i++ ) {
              $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
              if ($tmpFilePath != ""){
                $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                  $filename_arr[] = $newFilePath;
                  $filename_arr1[] = $newFilePath1;

                }
              }
            }
            $file_names = implode(',', $filename_arr1);
            var_dump($file_names); exit;

Comments

0
foreach ($_FILES['image']['name'] as $key => $val) {
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
$fileName = basename($_FILES['image']['name'][$key]);
$tempName = basename($_FILES['image']['tmp_name'][$key]);
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$fileNameFinal = $empID . '_' . date('Y-m-d_His') . '.' . $fileExt;

if (in_array($fileExt, $allowTypes)) {
    if (move_uploaded_file($_FILES['image']['tmp_name'][$key], 'uploads/' . $fileNameFinal)) {

        $insert = $conn->query("INSERT INTO apimultiimage (EmployeeID, token, image) VALUES('" . $empID . "','" . $token . "','" . $fileNameFinal . "')");

        $result['msg'] = 'Inserted.';
        $result['status'] = 1;
    } else {
        $result['msg'] = 'Not Inserted.';
        $result['status'] = 0;
    }
} else {
    $result['msg'] = 'Please select a file type jpg / jpeg / png / gif to upload.';
    $result['status'] = 0;
}

}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Multiple image upload with other table $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());
       

  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);
        
      }

in ajax

$(document).ready(function() {
    $('#addCAT').validate({
        rules: {
            name: required: true
        }
        submitHandler: function(form) {
            var formurl = $(form).attr('action');
            $.ajax({
                url: formurl,
                type: "POST",
                data: new FormData(form),
                cache: false,
                processData: false,
                contentType: false,
                success: function(data) {
                    window.location.href = "{{ url('admin/listcategory')}}";
                }
            });
        }
    })
})

Comments

-1

jQuery(document).ready(function ($) {
  $(function () {
    let filesArray = [];

    function updateInputField(input, files) {
      input.value = "";
      const dataTransfer = new DataTransfer();
      files.forEach((file) => dataTransfer.items.add(file));
      input.files = dataTransfer.files;
    }

    function displayImages(input, placeToInsertImagePreview) {
      const gallery = $(placeToInsertImagePreview);
      gallery.empty();

      filesArray.forEach((file, index) => {
        const reader = new FileReader();
        const currentIndex = index;

        reader.onload = function (event) {
       

          const wrapper = $("<div>")
            .addClass("image-wrapper")
            .attr("data-flag", currentIndex);

          $("<img>")
            .attr("src", event.target.result)
            .attr("height", "100px")
            .attr("width", "100px")
            .appendTo(wrapper);

          $("<button>")
            .addClass("btn-close")
            .on("click", function () {
              filesArray.splice(currentIndex, 1);
              $(".featured_image_key").val("");
              updateInputField(input, filesArray);

              displayImages(input, placeToInsertImagePreview);
            })
            .appendTo(wrapper);

          wrapper.appendTo(gallery);
        };

        reader.readAsDataURL(file);
      });
    }

    $("#gallery-photo-add").on("change", function () {
      filesArray = Array.from(this.files);
      console.log(filesArray);
      if (filesArray.length > 5) {
        Swal.fire({
          text: "Please Select only 5 images",
          title: "Error",
          icon: "error",
        });
        filesArray = [];
        this.value = "";
        $(".gallery").empty();
        return;
      }
      displayImages(this, ".gallery");
    });
  });

  $(document).on("click", ".image-wrapper", function () {
    $(".image-wrapper").removeClass("addBorder");
    $(this).addClass("addBorder");
    var flag = $(this).data("flag");
    $(".featured_image_key").val("").val(flag);
  });

  $("#formData").on("submit", function (e) {
    e.preventDefault();
    console.log("Submitted");
    var formData = new FormData(this);
    formData.append("action", "create_wc_product");
    $.ajax({
      url: ajaxObject.ajaxUrl,
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function (response) {
        if (response.success) {
          $(".alert")
            .removeClass("alert-danger")
            .addClass("alert-success")
            .html("")
            .html(response.data.message);
           $("#formData")[0].reset();
        } else {
          $(".alert")
            .removeClass("alert-success")
            .addClass("alert-danger")
            .html("")
            .html(response.data.message);
        }
      },
      error: function (xhr, error, status) {
        alert("Ajax Error:" + error);
      },
    });
  });
});
.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-wrapper {
  position: relative;
  display: inline-block;
}

.btn-close {
  position: absolute;
  top: 0;
  right: 0;
  background: red;
  color: white;
  border: none;
  cursor: pointer;
}

img {
  height: 100px;
  width: 100px;
}

.addBorder {
  border: 2px solid rgb(14, 177, 227);
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- Option 1: Include in HTML -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">

<div class="container w-100">
    <div class="row">
        <div class="col d-flex justify-content-center align-items-center">
            <div class="card shadow-lg w-50 bg-light">
                <div class="card-header ">
                    <h4 class="text-center">Add New Product</h4>
                </div>
                <div class="card-body">
                    <form id="formData">
                        <div class="form-group m-3">
                            <label for="productImages">Product Images</label>
                            <input type="file" name="productImages[]" id="gallery-photo-add" class="form-control" placeholder="Select Product Images" multiple>
                        </div>
                        <div class="gallery"></div>
                        <div class=" d-flex justify-content-center align-items-center">
                            <button type="submit" class="btn btn-outline-primary">Add Product</button>
                        </div>



                        <div class="alert my-2"></div>
                    </form>
                </div>
            </div>
        </div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.