In this section, we will provide a short code example showing how to handle file uploads in a controller action method. We will attract reader's attention to the aspects specific to file uploads.
Assume we want to add a web page displaying a form (let's name it YourForm
) capable of file uploads.
For that page, we need to add the uploadAction()
method to a controller class:
<?php
//...
class IndexController extends AbstractActionController
{
// This is the "upload" action displaying the Upload page.
public function uploadAction()
{
// Create the form model.
$form = new YourForm();
// Check if user has submitted the form.
if($this->getRequest()->isPost()) {
// Make certain to merge the files info!
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
// Pass data to form.
$form->setData($data);
// Execute file validators.
if($form->isValid()) {
// Execute file filters.
$data = $form->getData();
// Redirect the user to another page.
return $this->redirect()->toRoute('application', ['action'=>'index']);
}
}
// Render the page.
return new ViewModel([
'form' => $form
]);
}
}
As you can see from the code above, the uploadAction()
looks like a usual controller action
implementing a typical form workflow, however it has some aspects specific to file uploads (marked
with bold):
In line 9, we create an instance of the YourForm
form model with the help of the new
operator.
In line 12, we check whether the request is an HTTP POST request. If so, we get the data from $_POST
and $_FILES
super-global PHP arrays and merge them into the single array (lines 15-19). This is
required to correctly handle uploaded files, if any. Then we pass this array to the form model with
the setData()
method (line 22).
In line 25, we call the form model's isValid()
method. This method runs the input filter attached
to the form model. For FileInput
inputs, this will execute attached validators only.
If the data is valid, we call the getData()
method (line 28). For the FileInput
inputs, this
will run the attached file filters. The file filters, for example, could move the uploaded files
to the directory of residence.
On success, in line 31, we redirect the user to the "index" action of the controller.
In the controller action above, you should remember three things: 1) merge
$_POST
and$_FILES
super-global arrays before you pass them to the form'ssetData()
method; 2) useisValid()
form's method to check uploaded files for correctness (run validators); 3) usegetData()
form's method to run file filters.