Recently I was asked how to rename a file with the Zend Framework that used a Zend Form and Zend File element. They key requirement was that it should not be a hack or a kludged solution. So I thought I’d write a quick post to provide a simple example on how it was achieved.
So the first method that came to mind was a file filter. At first I thought that I may have to write my own, but then, on going through the available file filters that come with the standard Zend library, I found the rename filter - which did exactly what was needed. Ok, so let’s skip to the chase and show the code, then we’ll go through it.
The Code
public function fileUploadAction()
{
$form = new Zend_Form;
$form->setAction(&'/default/index/file-upload')
->setMethod(&'post');
$uploadFile = new Zend\_Form\_Element_File(&'uploadfile');
$uploadFile->addFilter(new Zend\_Filter\_File_Rename(array(&'target' => &'config.ini')))
->setRequired(true)
->setLabel(&'Upload file:');
$form->addElement($uploadFile);
$form->addElement(new Zend\_Form\_Element_Submit(&'submit'));
if ($form->isValid($_POST)) {
$values = $form->getValues();
$this->view->messages = array(&'File uploaded');
}
$this->view->form = $form;
}
In the code above, we have a pretty standard, and simple, Zend Form setup. We’ve set the action and method of the form itself. After that we’ve created a file element to add to the form.
On the element, we’ve set the label and the required flag, so that required as part of the validation process. Nothing too difficult here.
Then we get to the core work - we add a filter on it. The filter used is the Zend Filter File Rename. In it, we’ve set only one parameter - target. Let’s look at the available configuration options and I’ll cover why just target is set.
Zend File Filter Rename Options
The file rename filter takes three arguments:
- source - The file (or directory) to rename
- target - The new file (or directory) name
- overwrite - True/False indicating whether to overwrite an existing file of the same name or not
Given that the file’s name been set by the name of the file element, in this case uploadfile there’s no need to specify source. Also, in this simple example, there will be no existing file located in the upload directory, so there’s no need to worry about overwriting it.
So we can skip this option as well. All that’s needed to be done is to set target, which specifies what the file will be renamed to after validation has occurred - in this case &’config.ini&’. So now, when you run this and you look in your PHP temp directory, you’ll see a new file called &’config.ini&'.
Can this help you? Do you see problems with this approach? Tell us your thoughts in a comment or via twitter.
Join the discussion
comments powered by Disqus