phpzend-frameworkzend-formzend-filterzend-file

Zend File Upload Rename Error


I am uploading three files using Zend Element File. I am uploading and renaming the files. Now the problem is that when uploading same extension, it generates error of

Zend_Filter_Exception: File 'D:\wamp2\tmp\php2443.tmp' could not be renamed. It already exists.

For example if in first file I upload file of extenstiono .txt in second I upload .docx and in third I again select .txt or .docx, It will generate the above given error.

But If I select three different extensions, every thing goes best. I am using the following code

  if ($form->med_file_1->isUploaded()) {

    $originalFilename = pathinfo($form->med_file_1->getFileName());

    $newFilename = time() . '.' . $originalFilename['extension'];
    $form->med_file_1->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
    $form->med_file_1->receive();

}

 if ($form->med_file_2->isUploaded()) {

    $originalFilename = pathinfo($form->med_file_2->getFileName());
    $newFilename = time() . '.' . $originalFilename['extension'];
    $form->med_file_2->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
    $form->med_file_2->receive();

}

    if ($form->med_file_3->isUploaded()) {
                $originalFilename = pathinfo($form->med_file_3->getFileName());
                $newFilename = time() . '.' . $originalFilename['extension'];
                $form->med_file_3->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
                $form->med_file_3->receive();

    }

Solution

  • The reason for the error is because you are naming each uploaded file:

    time() . '.' . $originalFilename['extension'];
    

    The call to receive() happens so fast that time() returns the same value on each call so you can end up with duplicate file names. You just need to generate a more unique name for each file. Something like the following should work:

    md5(uniqid(time(), true)) . '.' . $originalFilename['extension'];
    //or
    $originalFilename['basename'] . '_' . time() . '.' . $originalFilename['extension'];