A free and open-source book on ZF3 for beginners


10.7. Controller Action & File Uploads

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 the controller action above, you should remember three things: 1) merge $_POST and $_FILES super-global arrays before you pass them to the form's setData() method; 2) use isValid() form's method to check uploaded files for correctness (run validators); 3) use getData() form's method to run file filters.


Top