user2729578
user2729578

Reputation: 13

Multiple Photo Upload PHP

I've looked around and have struggled to find out how to upload multiple images (.jpg/.png/etc). For my task I was looking to upload 5 pictures to the database record. So far I'm struggling to even upload 5 together in one record. I've used PHP from the Ws3 website and it works successfully but this code is for one image alone.

PHP Code -

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

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
  if ($_FILES["file"]["error"] > 0)
  {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  }
  else
  {

    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {

    }
    else
    {
        move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . uniqid() . "_" . $_FILES["file"]["name"]);
    }
  }
}
else
{
    $error =  "Invalid file";
}

My HTML is as follows,

<label for="file">Filename:</label>
        <input type="file" name="file" id="file">

        <input type="file" name="file" id="file">

        <input type="file" name="file" id="file">

        <input type="file" name="file" id="file">

        <input type="file" name="file" id="file">

Any advice is greatly appreciated guys! Cheers

Upvotes: 0

Views: 11733

Answers (3)

Kahfii Setiawan
Kahfii Setiawan

Reputation: 1

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

    $jumlah = count($_FILES['gambar']['size']);     // cari jml gambar 
    $size = $_FILES['gambar']['size'];              //cek ukuran file
    $ext = $_FILES['gambar']['type'];               // cek extensi file
    $max_size = 1000000;
    $htg = implode(" ",$size);

    if ($htg < 1){
        echo "<script>alert('pilih file yang akan di upload !');
        location.href='index.php';</script>";
    }   
    elseif(max($size) > $max_size){
        echo "<script>alert('ukuran file terlalu besar');
        location.href='index.php';</script>";
    }elseif (in_array("application/octet-stream", $ext) || in_array("application/pdf",$ext) || in_array("text/plain", $ext)) {
        echo "<script>alert('file harus jpg atau png semua !');
        location.href='index.php';</script>";
    }else{   
          for ($i=0; $i < $jumlah; $i++) { 
                $file_name = $_FILES['gambar']['name'][$i];
                $tmp_name = $_FILES['gambar']['tmp_name'][$i];          
                move_uploaded_file($tmp_name, "uploads/".$file_name);

                mysqli_query($conn,"INSERT INTO images VALUES
                ('','$file_name','$tmp_name')");                
            }
            echo "<script>alert('Upload Berhasil');location.href='index.php';</script>";
    }
}

Upvotes: 0

macnewbold
macnewbold

Reputation: 130

I think the problem is in your HTML... instead of five of these:

<input type="file" name="file" id="file">

Try doing it like this:

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

That will submit an array of files, rather than trying to submit multiple files under the same input name.

As a side note, you shouldn't use the same id attribute on more than one element. Perhaps you meant to use a class?

Upvotes: 0

Joran Den Houting
Joran Den Houting

Reputation: 3163

First, add enctype="multipart/form-data" to your form. Then change the names of the file fields to:

<input type="file" name="file[]" id="file" >
<input type="file" name="file[]" id="file" >
<input type="file" name="file[]" id="file" >

This will create an array of the files submitted. Now you'll be able to do a foreach on the files. Quick example:

foreach ($_FILES['file']['name'] as $f => $name) {

}

Around your existing code, then add [$f] to every $_FILES["file"] variable. So $_FILES["file"]["size"] has to be changed to $_FILES["file"]["size"][$f] and so on. In the foreach I referring $name to $_FILES["file"]["name"][$f], so you can use $name instead.

Full php code based on your script:

foreach ($_FILES['file']['name'] as $f => $name) {
 $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $name);
    $extension = end($temp);

if ((($_FILES["file"]["type"][$f] == "image/gif")
|| ($_FILES["file"]["type"][$f] == "image/jpeg")
|| ($_FILES["file"]["type"][$f] == "image/jpg")
|| ($_FILES["file"]["type"][$f] == "image/png"))
&& ($_FILES["file"]["size"][$f] < 2000000)
&& in_array($extension, $allowedExts))
{
  if ($_FILES["file"]["error"][$f] > 0)
  {
    echo "Return Code: " . $_FILES["file"]["error"][$f] . "<br>";
  }
  else
  {

    if (file_exists("upload/" . $name))
    {

    }
    else
    {
        move_uploaded_file($_FILES["file"]["tmp_name"][$f], "upload/" . uniqid() . "_" . $name);
    }
  }
}
else
{
    $error =  "Invalid file";
}
}

At the end, I would suggest you to go learn more about PHP on different sites. W3schools is easy, but also not your best option. As an example, you are checking this:

    if ((($_FILES["file"]["type"][$f] == "image/gif")
|| ($_FILES["file"]["type"][$f] == "image/jpeg")
|| ($_FILES["file"]["type"][$f] == "image/jpg")
|| ($_FILES["file"]["type"][$f] == "image/png"))
&& ($_FILES["file"]["size"][$f] < 2000000)
&& in_array($extension, $allowedExts))

But only the array will be enough, like this:

    if ($_FILES["file"]["size"][$f] < 2000000 && in_array($extension, $allowedExts))

$_FILES["file"]["type"] not always returns the type as expected.. We see it many times in audio and video files. Another post on SO about MIME types referring to the W3schools script: PHP: $_FILES["file"]["type"] is useless

Before asking new questions on StackOverflow, please do a search. I just wrote a long answer just for you, but the same thing has been done MANY times for this kind of question already. https://stackoverflow.com/search?q=multiple+upload+php

Hope it answers your question, and good luck learning PHP.

Upvotes: 6

Related Questions