0

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

Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
user2729578
  • 13
  • 1
  • 2
  • 6
  • You cannot have multiple fields with the same name and expect it to work. Try it with `name="file[]"` to create an array – PeeHaa Oct 30 '13 at 15:22
  • 2
    Instead of that long if statement use: `if(in_array(array("image/gif", image/jpg, "image/jpg", "image/png"), $_FILES["file"]["type"])` to avoid repeating yourself. – Matt Harrison Oct 30 '13 at 15:23
  • 1
    1.) Don't use W3schools - they provide outdated and bad information. 2.) The file upload PHP is valid only when there's 1 file uploaded. 3.) HTML you're using is not only invalid (id element is supposed to be unique across the document), it's not going to help you upload multiple files since name should be `name="file[]"`, which creates an array of files (note the square brackets). – N.B. Oct 30 '13 at 15:24
  • @MattHarrison, why would you still check on MIME types? Look at my answer, they are useless.. – Joran Den Houting Oct 30 '13 at 15:41
  • @JoranDenHouting I was commenting purely on syntax not approach. – Matt Harrison Oct 30 '13 at 15:43
  • @N.B.Had no idea, the college I go to recommend using it too - shocking!! Thanks for the advice – user2729578 Oct 30 '13 at 16:35
  • @user2729578 - [check here why it's not advisable to use w3schools](http://www.w3fools.com/) – N.B. Oct 30 '13 at 18:50

3 Answers3

6

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.

Community
  • 1
  • 1
Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
  • Hi @Joran. Thanks for taking the time to reply. I have done extensive search and couldn't see an answer to my question. Hard to wean out the nonsense answers. Apologises if you have already posted something similar - didn't see it! Cheers again! – user2729578 Oct 30 '13 at 16:33
0

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?

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
macnewbold
  • 135
  • 3
0
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>";
    }
}
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Tiago Martins Peres Oct 17 '18 at 08:47