title: PHP: How to rename a file uploaded with Zend_Form_Element_File?
body: <h2>Form:</h2>
  
  <pre><code>//excerpt
  $file = new Zend_Form_Element_File('file');
  $file-&gt;setLabel('File to upload:')
      -&gt;setRequired(true)
      -&gt;addValidator('NotEmpty')
      -&gt;addValidator('Count', false, 1)
      -&gt;setDestination(APPLICATION_UPLOADS_DIR);
  $this-&gt;addElement($file);
  </code></pre>
  
  <h2>Controller:</h2>
  
  <pre><code>//excerpt
  if ($form-&gt;isValid($request-&gt;getPost()) {
      $newFilename = 'foobar.txt';
      //how should I rename the file?
      //When should I rename the file? Before or after receiving?
      try {
          $form-&gt;file-&gt;receive();
          echo 'filename: '. $form-&gt;file-&gt;getFileName();
      }
  }
  </code></pre>
  
  <h2>Questions:</h2>
  
  <ol>
  <li><p>When I call <code>$form-&gt;file-&gt;getFileName()</code> it returns the full path, not just the file name. How can I output just the name of the file?</p>
  
  <pre><code>//Answer: First, get an array of the parts of the filename:
  $pathparts = pathinfo($form-&gt;file-&gt;getFileName());
  //then get the part that you want to use
  $originalFilename = $pathparts['basename'];
  </code></pre></li>
  <li><p>How can I rename the filename to something I want? Can this be done with the <code>Rename</code> filter? I'm already setting the destination in the form, so all I want to do is change the filename. Maybe I shouldn't be setting the destination in the form? Or maybe this can't be done with a filter. Maybe I should be doing this with a PHP function? What should I do?</p>
  
  <pre><code>//Answer: Use the rename filter:
  $form-&gt;file-&gt;addFilter('Rename', 'new-file-name-goes-here.txt');
  </code></pre></li>
  </ol>
  
  <h2>Final Solution:</h2>
  
  <p>This is what I ended up doing:</p>
  
  <pre><code>public function foobarAction()
  {
      //...etc...
  
      if (!$form-&gt;isValid($request-&gt;getPost())) {
          $this-&gt;view-&gt;form = $form;
          return;
      }
  
      //the following will rename the file (I'm setting the upload dir in the form)
      $originalFilename = pathinfo($form-&gt;file-&gt;getFileName());
      $newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension'];
      $form-&gt;file-&gt;addFilter('Rename', $newFilename);
  
      try {
          $form-&gt;file-&gt;receive();
          //upload complete!
          $file = new Default_Model_File();
          $file-&gt;setDisplayFilename($originalFilename['basename'])
              -&gt;setActualFilename($newFilename)
              -&gt;setMimeType($form-&gt;file-&gt;getMimeType())
              -&gt;setDescription($form-&gt;description-&gt;getValue());
          $file-&gt;save();
      } catch (Exception $e) {
          //error: file couldn't be received, or saved (one of the two)
      }
  }
  </code></pre>