Multiple file upload error?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rahulephp
    New Member
    • Sep 2009
    • 59

    Multiple file upload error?

    i think i am missing something in the below script:
    It shows error an do not upload files to destination:

    Let me know how to solve this:

    Code:
      <?php
    
      if (isset($_POST[submit])) 
      {
      $uploadArray= array();
      $uploadArray[] = $_POST['uploadedfile'];
      $uploadArray[] = $_POST['uploadedfile2'];
      $uploadArray[] = $_POST['uploadedfile3'];
    
    	  foreach($uploadArray as $file) 
    	  {
    		  $target_path = "upload/";
    		  $target_path = $target_path . basename( $_FILES["$file"]['name']);
    		
    			if(move_uploaded_file($_FILES["$file"]['tmp_name'], $target_path)) 
    				{
    				echo "The file ". basename( $_FILES["$file"]['name'])." has been uploaded";
    				}
    		   else
    					{
    				echo "There was an error uploading the file, please try again!";
    				 }
      		}
      }
      ?>
    
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
      <title>Untitled Document</title>
      </head>
    
      <body>
      <form enctype="multipart/form-data" action="" method="POST">
      <p>
     	 <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
      Choose a file to upload:
      <input name="uploadedfile" type="file" />
      </p>
      <p>Choose a file to upload:
      <input name="uploadedfile2" type="file" />
      </p>
      <p>Choose a file to upload:
      <input name="uploadedfile3" type="file" />
      <br />
      <input name="submit" type="submit" id="submit" value="submit" />
      </p>
      </form>
      </body>
      </html>
    Error Msg:
    Code:
    Notice: Undefined index: in E:\wamp\www\fileupload\index.php on line 25
    There was an error uploading the file, please try again!
    Notice: Undefined index: in E:\wamp\www\fileupload\index.php on line 22
    
    Notice: Undefined index: in E:\wamp\www\fileupload\index.php on line 25
    There was an error uploading the file, please try again!
    Notice: Undefined index: in E:\wamp\www\fileupload\index.php on line 22
    
    Notice: Undefined index: in E:\wamp\www\fileupload\index.php on line 25
    There was an error uploading the file, please try again!
    Last edited by Dormilich; Dec 14 '09, 02:03 PM. Reason: contracting the code a bit
  • kovik
    Recognized Expert Top Contributor
    • Jun 2007
    • 1044

    #2
    I think that Bytes.com's [code] tags are glitchy... Your code has seemingly random HTML entities scattered about and, in "Expand" mode, the ampersands are all converted to "&amp;". So, I'll try to ignore the HTML entities when responding. It's also be nice if Bytes.com had syntax highlighting. *ahem* Anyway...


    Basically, your main problem seems to be this undefined index. Your error message has no entry for the undefined index, as you can see. This is because it is looking for index "". That's an empty string, and likely not what you were going for. On lines 22 and 25, you are attempting to look at $_FILES["$file"]. $file is defined in your foreach loop as an element of $uploadArray. However, your $uploadArray array consists of $_POST data which is, firstly, nonexistent for your upload form and, secondly, wouldn't be a scalar value (i.e. string, integer) if you were using the correct array, $_FILES, anyway. Therefore, it results in an empty value.


    I have two suggestions for you:

    1. Make use of form arrays in your form.

    Code:
    <form action="#" method="post" enctype="multipart/form-data">
        <input type="file" name="files[]" />
        <input type="file" name="files[]" />
        <input type="file" name="files[]" />
        <button type="submit">Upload</button>
    </form>
    When this is submitted, $_FILES['files'] will be an array of 3 uploaded files, in the order that they exist in the form. This also provides you with the flexibility of having a variable amount of uploaded files, and grants you the ability to add more input fields dynamically (i.e. via JavaScript) without changing any of the back-end code.

    2. Traverse the form array for uploading.

    Code:
    if (!empty($_FILES)) {  // Form has been submitted
        if (!empty($_FILES['files']) && is_array($_FILES['files'])) {  // The file array is formatted correctly
            for ($i = 0; $i < sizeof($_FILES['files']['name']); $i++) {
                // Perform upload with $_FILES['files'][<attribute>][$i]
            }
        }
    }
    You cannot use a foreach loop when you upload multiple files together in a form array, sadly, because PHP organizes them differently. You'd think that each element of the $_FILES['files'] array would be an individual input field from the form, but instead PHP forces it to conform with the "$_FILES[<name>][<attribute>]" format. This is done for safety reasons, though I personally feel we should at least have an option. Not that my personal opinion matters. :P

    Anyway, what this means is that, for example, in order to get the temporary file name of the first uploaded file, you would look at $_FILES['files']['tmp_name'][0]. To get the temporary file name of the second uploaded file, you look at $_FILES['files']['tmp_name'][1]. And so on. This is why we need a for loop, instead of a foreach loop, so that we can use $i as the index to check.

    Comment

    • rahulephp
      New Member
      • Sep 2009
      • 59

      #3
      Hey thanks for your reply,

      I have achived this in folowing way:

      Code:
      $image_count = count($_FILES[image][name]);
      //db($_FILES);
      for($i = 0; $i < $image_count; $i++)
      	{
      
              $src = $_FILES['image']['tmp_name'][$i];
      
             $destination = BASE_DIR . 'upload/' .$_FILES['image']['name'][$i];
              if (move_uploaded_file($src, $destination))
              {
                  chmod($destination, 0664);
      			$detail[temp_image]=$_FILES['image']['name'];
              }
              else
              {
                  die('Sorry, the system was unable to upload the project image.');
              }
      	}

      Comment

      • rahulephp
        New Member
        • Sep 2009
        • 59

        #4
        Hey thanks for your reply,

        However, I have achieved this in following way,

        Code:
        $image_count = count($_FILES[image][name]);
        //db($_FILES);
        for($i = 0; $i < $image_count; $i++)
        	{
        
                $src = $_FILES['image']['tmp_name'][$i];
        
               $destination = BASE_DIR . 'upload/' .$_FILES['image']['name'][$i];
                if (move_uploaded_file($src, $destination))
                {
                    chmod($destination, 0664);
        			$detail[temp_image]=$_FILES['image']['name'];
                }
                else
                {
                    die('Sorry, the system was unable to upload the project image.');
                }
        	}
        
        $image=$detail[temp_image];
        Thanks again for your response.

        Comment

        • kovik
          Recognized Expert Top Contributor
          • Jun 2007
          • 1044

          #5
          Why do you reassign $detail['temp_image'] every time a file is successfully uploaded?

          Also, don't forget to wrap your array keys in quotation marks. When you don't, then PHP assumes that you meant a constant. It wastes time looking for that constant before determining that you meant a string. And, if it does find a constant, it will overwrite your string.

          Like this:
          $detail[temp_image] should be $detail['temp_image']
          $_FILE[image][name] should be $_FILES['image']['name']

          Comment

          Working...