4

Trying to build a multiple image upload that takes the 3 submitted files from my form and stores them on my server.

I have the following but no matter what I receive "Invalid file" can anybdoy see where im going wrong?

for($i = 0; $i < 3; $i++) {
 $aFile = $_FILES['file'][$i];




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


        if (file_exists("upload/" . $aFile["file"]["name"]))
          {
          echo $aFile["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($aFile['tmp_name'],
          "upload/" . date('U')."-".$aFile["file"]["name"]);  // add a unique string to the uploaded filename so that it is unique.
          echo "Image Uploaded Successfully";
          }
        }
      }
    else
      {
      echo "Invalid file";

    }

}

** HTML **

<li>
    <label for="picture_1">picture 1 : </label>
    <input type="file" name="file">
</li>
<li>
    <label for="picture_2">picture 2 : </label>
    <input type="file" name="picture_2">
</li>
<li>
    <label for="picture_3">picture 3 : </label>
    <input type="file" name="picture_3">
</li>
5
  • Check which boolean in the if statement is false? Debugging 101.
    – Halcyon
    Dec 18, 2012 at 16:56
  • have u tried to upload a single file first? Dec 18, 2012 at 17:01
  • Show your HTML. Your html input file name may be wrong.
    – Sithu
    Dec 18, 2012 at 17:02
  • Ive tried a single file and that works @arunu...
    – Liam
    Dec 18, 2012 at 17:13
  • check this link.Its similar to ur problem stackoverflow.com/questions/8761066/… Dec 18, 2012 at 17:24

2 Answers 2

1

As I guess, the main problem is your HTML element names and the names used in $_FILES cannot be matched, i.e., you used the first file input name "file". It should be "picture_1". And you used the index 0 to 2 on your file handling part. It should be 1 to 3 to match "picture_1", "picture_2" and "picture_3".

Note that your form should have enctype="multipart/form-data", otherwise your files will not be uploaded. Here is the correct one:

There are two approaches to implement this :
(1) Naming file inputs separately such as picture_1, picture_2, etc.
(2) Naming file inputs as a group such as file[].

APPROACH 1: Naming file inputs separately

HTML

<form method="post" enctype="multipart/form-data">
    <li>
        <label for="picture_1">picture 1 : </label>
        <input type="file" name="picture_1" id="picture_1" />
    </li>
    <li>
        <label for="picture_2">picture 2 : </label>
        <input type="file" name="picture_2" id="picture_2" />
    </li>
    <li>
        <label for="picture_3">picture 3 : </label>
        <input type="file" name="picture_3" id="picture_3" />
    </li>
    <input type="submit" name="submit" value="Upload" />
</form>

PHP

if(sizeof($_FILES)){ 
    for($i = 1; $i <= 3; $i++) {
     $aFile = $_FILES['picture_'.$i];
     if(empty($aFile['tmp_name'])) continue; # skip for empty elements

        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $extension = end(explode(".", $aFile["name"]));
        if ((($aFile["type"] == "image/gif")
        || ($aFile["type"] == "image/jpeg")
        || ($aFile["type"] == "image/png")
        || ($aFile["type"] == "image/pjpeg"))
        && ($aFile["size"] < 20000)
        && in_array(strtolower($extension), $allowedExts))
          {
          if ($aFile["error"] > 0)
            {
            echo "Return Code: " .$aFile["error"] . "<br>";
            }
          else
            {       
            if (file_exists("upload/" . $aFile["name"]))
              {
              echo $aFile["name"] . " already exists. ";
              }
            else
              {
              move_uploaded_file($aFile['tmp_name'], 
                "upload/" . date('U')."-".$aFile["name"]); 
              echo "Image Uploaded Successfully";
              }
            }
          }
        else
        {
          echo "Invalid file";  
        }
    }
}

APPROACH 2: Naming file inputs as a group

HTML

<form method="post" enctype="multipart/form-data">
    <li>
        <label for="picture_1">picture 1 : </label>
        <input type="file" name="file[]" id="picture_1" />
    </li>
    <li>
        <label for="picture_2">picture 2 : </label>
        <input type="file" name="file[]" id="picture_2" />
    </li>
    <li>
        <label for="picture_3">picture 3 : </label>
        <input type="file" name="file[]" id="picture_3" />
    </li>
    <input type="submit" name="submit" value="Upload" />
</form>

PHP

if(sizeof($_FILES)){        
    for($i = 0; $i < 3; $i++) {
        $name       = $_FILES['file']['name'][$i];
        $type       = $_FILES['file']['type'][$i];
        $tmp_name   = $_FILES['file']['tmp_name'][$i];
        $error     = $_FILES['file']['error'][$i];
        $size       = $_FILES['file']['size'][$i];

        if(empty($name)) continue; # skip for empty element

        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $extension = end(explode(".", $name));
        if ((  ($type == "image/gif")
            || ($type == "image/jpeg")
            || ($type == "image/png")
            || ($type == "image/pjpeg"))
            && $size < 20000
            && in_array(strtolower($extension), $allowedExts) )
          {
          if ($error > 0)
            {
            echo "Return Code: " .$error . "<br>";
            }
          else
            {               
            if (file_exists("upload/" . $name))
              {
              echo $aFile["file"]["name"] . " already exists. ";
              }
            else
              {
              move_uploaded_file($tmp_name,
              "upload/" . date('U')."-".$name); 
              echo "Image Uploaded Successfully";
              }
            }
          }
        else
          {
          echo "Invalid file";      
        }       
    }
}

CREDITS:

  • File extensions should be checked with lower cases using strtolower().
  • If you use <label for="some_id">, you can have the same ID attribute in your respective HTML element, e.g., <input type="file" name="..." id="some_id" />. When you click the label, the onclick event of the element will be triggered.
0

The file size is expressed in bytes.

One of the conditions is a filesize limit check: ($aFile["file"]["size"] < 20000)

That's lowers the filesize limit to 20 KB.

It might just happen that you exceeded that limit.

Check the size of the files you are uploading.

Update

This is how the files structure looks like when submitting three upload fields:

array (size=1)
  'file' => 
    array (size=5)
     'name' => 
        array (size=3)
          1 => string 'all_products (6).csv' (length=20)
          2 => string 'pricero (3).csv' (length=15)
          3 => string 'pricero.csv' (length=11)
      'type' => 
        array (size=3)
          1 => string 'application/octet-stream' (length=24)
          2 => string 'application/octet-stream' (length=24)
          3 => string 'application/octet-stream' (length=24)
      'tmp_name' => 
        array (size=3)
          1 => string 'E:\server\wamp\tmp\phpEF79.tmp' (length=30)
          2 => string 'E:\server\wamp\tmp\phpEF7A.tmp' (length=30)
          3 => string 'E:\server\wamp\tmp\phpEF7B.tmp' (length=30)
      'error' => 
        array (size=3)
          1 => int 0
          2 => int 0
          3 => int 0
      'size' => 
        array (size=3)
          1 => int 29702
          2 => int 23095
          3 => int 23095

There is something wrong with your $aFile variable. I tried to run your script and got errors (Undefined index and the like).

1
  • are the file extensions containing uppercase letters? That also can be a problem. (My apologies, if you are a linux/unix user :))
    – beerwin
    Dec 18, 2012 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.