Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

22

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Tôi đã cố gắng thực hiện công việc này khá lâu rồi. Nhưng tôi dường như không thể làm cho nó hoạt động. Tôi muốn có một biểu mẫu tải lên nhiều hình ảnh chỉ bằng một đầu vào.

Đây là tải lên của tôi.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";
        }
    }
} 
?>

Nếu tôi lấy ra các dòng

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

Với khung đóng tương ứng, nó dường như hoạt động tốt. Hình ảnh được tải lên hoàn hảo. Nhưng vấn đề là, nó chỉ cho phép tôi tải lên một.

Xin vui lòng tôi thực sự cần chuyên môn của bạn. Cảm ơn

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

Graddev

3814 Huy hiệu bạc14 Huy hiệu đồng4 silver badges14 bronze badges

Đã hỏi ngày 22 tháng 7 năm 2014 lúc 18:37Jul 22, 2014 at 18:37

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

2

$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, ");
    }
}

Và bạn phải kiểm tra mã HTML của mình

<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>

Liên kết đẹp trên:

PHP đơn tải lên với sự giải thích cơ bản khác nhau..

Tải lên tệp PHP với xác thực

Tải lên nhiều tệp php với xác thực Bấm vào đây để tải về mã nguồn

Tải lên nhiều tệp php/jQuery lên với ProgressBar và xác thực (bấm vào đây để tải xuống mã nguồn)

Cách tải lên các tệp trong PHP và lưu trữ trong cơ sở dữ liệu MySQL (bấm vào đây để tải xuống mã nguồn)

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

Đã trả lời ngày 22 tháng 7 năm 2014 lúc 18:48Jul 22, 2014 at 18:48

9

Nhiều hình ảnh tải lên bằng mã nguồn đầy đủ PHP và xem trước có sẵn tại liên kết dưới đây. Mã mẫu:
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

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

Emil Condrea

9.4597 Huy hiệu vàng32 Huy hiệu bạc52 Huy hiệu Đồng7 gold badges32 silver badges52 bronze badges

Đã trả lời ngày 6 tháng 5 năm 2015 lúc 10:55May 6, 2015 at 10:55

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

Merbin Joemerbin JoeMerbin Joe

5923 Huy hiệu bạc26 Huy hiệu Đồng3 silver badges26 bronze badges

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";

}
?>

Ở đây $ file_name_all và $ filepath Nhận 1 tên tệp UPLODE 2 thời gian?$file_name_all And $filepath get 1 uplode file name 2 time?

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

Haridarshan

1.8581 Huy hiệu vàng23 Huy hiệu bạc37 Huy hiệu đồng1 gold badge23 silver badges37 bronze badges

Đã trả lời ngày 26 tháng 11 năm 2016 lúc 10:58Nov 26, 2016 at 10:58

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

1

Mã PHP

<?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>';

         }

     }
}

?>

Mã jQuery

<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>

Hoàn tác ♦

25.3K37 Huy hiệu vàng107 Huy hiệu bạc126 Huy hiệu đồng37 gold badges107 silver badges126 bronze badges

Đã trả lời ngày 13 tháng 8 năm 2016 lúc 12:31Aug 13, 2016 at 12:31

0

Nhạc hình ảnh lên với bảng khác $ sql1 = "chèn vào các giá trị sự kiện (tiêu đề) ('$ 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);
            }
        }

Và làm thế nào để lấy

$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);

      }

Trong ajax $ (document) .reet (function () {$ ('#addcat'). xác thực ({quy tắc: {name: abel: true} submitherler: function (form) 'Hành động'); $ .ajax ({url: formurl, loại: "post", data: new formdata (form), cache: false, processData: false, contentType: false .

Đã trả lời ngày 22 tháng 6 năm 2017 lúc 9:55Jun 22, 2017 at 9:55

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

Đã trả lời ngày 29 tháng 5 năm 2020 lúc 16:14May 29, 2020 at 16:14

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

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

}

Đã trả lời ngày 4 tháng 7 lúc 10:51Jul 4 at 10:51

Hướng dẫn how can i upload multiple images at a time in php? - Làm thế nào tôi có thể tải lên nhiều hình ảnh cùng một lúc trong php?

1

Làm cách nào để tải lên nhiều hình ảnh trong AJAX và PHP?

Php Ajax tải lên nhiều hình ảnh..
$ ("#UploadFile"). thay đổi (function () {.
$ ('#Image_Preview'). HTML ("") ;.
var Total_file = Document. getEuityById ("tải lên"). các tập tin. chiều dài;.
for (var i = 0; i
$ ('#Image_Preview'). nối ("") ;.

Làm thế nào tôi có thể di chuyển nhiều tải lên trong PHP?

Trong PHP, có thể tải lên nhiều tệp bằng một phần tử tệp đầu vào duy nhất.Bạn chỉ cần tùy chỉnh tệp tải lên tệp PHP và bật phần tử tệp của mình để chọn nhiều tệp ...
HTML.Dưới đây là một số bước để kích hoạt nhiều tệp tải lên.....
PHP.....
Đã hoàn thành mã.....
Thử nghiệm.....
Conclusion..

Làm cách nào để lưu trữ nhiều tệp trong PHP?

PHP trong tiếng Telugu..
Tên đầu vào phải được định nghĩa là một mảng tức là name = "inputName []".
Phần tử đầu vào phải có nhiều = "nhiều" hoặc chỉ nhiều ..
Trong tệp PHP, sử dụng cú pháp "$ _FILES ['inputName'] ['param'] [index]".
Tên tệp và đường dẫn trống phải được kiểm tra vì mảng có thể chứa các chuỗi trống ..

Làm cách nào để tải lên nhiều hình ảnh lên API?

Ở đây chúng tôi sử dụng thuộc tính bội = "đa" cho phép tải lên nhiều tệp.Duyệt và chọn nhiều tệp.Ở đây chúng tôi chọn 3 tệp hình ảnh ...
Xem túi.....
@Using (html. ....
Tải lên nhiều tập tin.
.