Unique filenames when uploading in Zend Framework

This is typical Zend Framework; needing a simple file upload as part of a Zend Form, I turned to the built in helpers and yes, it’s easy to upload a file with minimal additional code. So far so good.

But it defaults to uploading the file with the original filename and to overwriting existing files. I cannot remember a time when this was the behaviour I wanted from a file uploader; I always want to preserve existing files instead of overwriting them, and I usually want to give it some additional information in the filename or folder path – things like account or user IDs and timestamps for example, or just random hashes.

Eventually managed to find a way of customizing it that didn’t require three times the code saved by using Zend Framework in the first place, with grateful thanks to Dean Clatworthy:

$post = $request->getPost(); // This contains the POST params
 
        if ($request->isPost()) {
            if ($form->isValid($post)) {
 
                $upload = new Zend_File_Transfer_Adapter_Http();
                $filename = $upload->getFilename();
                $filename = basename($filename);
 
 
                $uniqueToken = md5(uniqid(mt_rand(), true));
                $filterRename = new Zend_Filter_File_Rename(array('target' => '/path/to/uploads/' . $uniqueToken.$filename, 'overwrite' => false));
                $upload->addFilter($filterRename);
 
                if (!$upload->receive()) {
                    $this->view->message = 'Error receiving the file';
                    return;
                }
 
                $this->view->message = 'Screenshot(s) successfully uploaded';
            }
        }

Unique filenames when uploading using Zend_Filter_File_Rename (Zend Framework).

Advertisements