Search code examples
phpuploadfile-rename

php rename 2 uploaded files to specific names before upload


I'm currently using the following code to upload and rename a single file..

Form..

<form method="post" enctype="multipart/form-data" name="formUploadFile">     
<label>Select file to upload:</label>
<input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="Upload" name="btnSubmit"/>
</form> 

and the follwing snippet of php does the magic..

     if($UploadOk == true){
                        $name = "foobar.csv";
                         move_uploaded_file($temp,$UploadFolder."/".$name);
                         array_push($uploadedFiles, $name);
}

But I'd now like to use it to upload 2 files and wish for the 1st to be renamed foobar.csv and the second to be renamed foobar2.csv how would I go about that?

I can upload the 2 files no problem, and rename the 1st also without issue my problem is in the renaming of the second file.

I've tried

$name = array("foobar.csv", "foobar2.csv"); 

and tried..

if($UploadOk == true){
                        $name = "foobar.csv";
                        $name2 = "foobar2.csv";
                        move_uploaded_file($temp,$UploadFolder."/".$name);
                        array_push($uploadedFiles, $name);
                        array_push($uploadedFiles, $name2);
                                    }

and also tried..

 if($UploadOk == true){
                            $name = "foobar.csv";
                            $name2 = "foobar2.csv";
                            move_uploaded_file($temp,$UploadFolder."/".$name);
                            array_push($uploadedFiles, $name, $name2);

                                        }

But none of these upload and rename the files.


Solution

  • You need to use the array of $_FILES['files']['tmp_name']. For example:

    if ( $UploadOk == true ) {
        $name = "foobar.csv";
        $name2 = "foobar2.csv";
        move_uploaded_file($_FILES['files']['tmp_name'][0], $UploadFolder."/".$name);
        move_uploaded_file($_FILES['files']['tmp_name'][1], $UploadFolder."/".$name2);
    }