title: PHP - Upload File Script in a For Loop
body: <p>So I have this form in a for loop which submits to itself and gets images uploaded by users, the form code:</p>
  
  <pre><code>    for ($x=1; $x&lt;=10; $x++)
      {
      echo "&lt;form method='post' enctype='multipart/form-data'&gt;";
  
      echo "
      &lt;label for='file'&gt;Image:&lt;/label&gt;
      &lt;input type='file' name='file'&gt;&lt;br&gt;
      &lt;input type='submit' name='submit' value='Upload Image'&gt;
      &lt;br&gt;";
  
      include ('lib/upload.php');
      }
  </code></pre>
  
  <p>the form will then call a script named "upload.php" which contains these codes:</p>
  
  <pre><code>    &lt;?php
       if (isset($_POST['submit']))
       {
          $allowedext=array("gif", "png", "jpeg", "jpg");
          $tmp=explode(".", $_FILES["file"]["name"]);
          $ext=end($tmp);
  
          if (
          (($_FILES["file"]["type"]=="image/gif") ||
          ($_FILES["file"]["type"]=="image/jpeg") ||
          ($_FILES["file"]["type"]=="image/jpg") ||
          ($_FILES["file"]["type"]=="image/pjpeg") ||
          ($_FILES["file"]["type"]=="image/png") ||
          ($_FILES["file"]["type"]=="image/x-png")) &amp;&amp;
          ($_FILES["file"]["size"]&lt;=3145728) &amp;&amp; in_array($ext, $allowedext)
          )
          {
              if ($_FILES["file"]["error"]&gt;0)
              {
                  echo "&lt;br&gt;Error: ".$_FILES["file"]["error"]."&lt;br&gt;";
              }
              else
              {
                  if (file_exists("upload/".$_FILES["file"]["name"]))
                  {
                      echo "&lt;br&gt;&lt;p style='color: #ff0000;'&gt;".$_FILES["file"]["name"]." already exists.&lt;/p&gt;&lt;br&gt;";
                  }
                  else
                  {
                      move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$_FILES["file"]["name"]);
                      $x="upload/".$_FILES["file"]["name"];
  
                      echo "&lt;br&gt;&lt;img src='$x' width='320px' height='240px'&gt;&lt;br&gt;";
                  }
              }
          }
          else if ($_FILES["file"]["size"]&gt;3145728)
          {
              echo "&lt;br&gt;&lt;p style='color: #ff0000;'&gt;File too large&lt;/p&gt;&lt;br&gt;";
          }
          else
          {
              echo "&lt;br&gt;&lt;p style='color:#ff0000;'&gt;Invalid file&lt;/p&gt;&lt;br&gt;";
          }
       }
      ?&gt;
  </code></pre>
  
  <p>So my problem is, everytime I upload an image, the error "Invalid File" comes up even though I'm pretty sure I uploaded a valid file. This works if I loop the form once, like this:</p>
  
  <pre><code>    for ($x=1; $x&lt;=1; $x++)
      {
          \\code
      }
  </code></pre>
  
  <p>any ideas what the problem could be?</p>