Question

I have a multiple image upload form on a page (up to 3) - but a user may choose to not upload 1 or more images at all. The script processing the the uploads when 1 or more are left blank gives me this error:

"Warning: copy() [function.copy]: Filename cannot be empty in"....

I have tried to use the code below to ignore the copy request if/when the field is empty but perform the copy if file upload exists but it is not working. Can someone tell me why this doesn't work or more appropriately how i need to code it differently?

FORM

<form id="form1" method="post" action="processor.php" enctype="multipart/form-data">

<div>
First Profile Image  <input name="ufile[]" type="file" /><br />
Second Profile Image <input name="ufile[]" type="file" /><br />
Third Profile Image  <input name="ufile[]" type="file" /><br />
<input type="submit" name="submit" id="submit" value="Submit" />

</div>

PHP in processor.php file

$pfi1= "upload/".$_FILES['ufile']['name'][0];
$pfi2= "upload/".$_FILES['ufile']['name'][1];
$pfi3= "upload/".$_FILES['ufile']['name'][2];
if ($_FILES['ufile']['name'][0] !=="" || $_FILES['ufile']['name'][0] !==NULL) {copy($_FILES['ufile']['tmp_name'][0], $pfi1);}
if ($_FILES['ufile']['name'][1] !=="" || $_FILES['ufile']['name'][1] !==NULL) {copy($_FILES['ufile']['tmp_name'][1], $pfi2);}
if ($_FILES['ufile']['name'][2] !=="" || $_FILES['ufile']['name'][2] !==NULL) {copy($_FILES['ufile']['tmp_name'][2], $fi3);}
Was it helpful?

Solution 2

As used in a comment on this link here: Multiple file upload in php Thanks to: Andy Braham for his input on that thread.

HTML

<input name="upload[]" type="file" multiple="multiple" />

PHP

//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

OTHER TIPS

you need to add file system level checks before using file manipulation functions such as copy.

Use is_file() or file_exists() first to check if it is ok to run copy() function on it

    if ($_FILES['ufile']['name'][0] !=="" 
       && $_FILES['ufile']['name'][0] !==NULL
       && file_exists("full/path/to/".$_FILES['ufile']['name'][0])
   )
   {
     copy...
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top