Asked  1 Year ago    Answers:  5   Viewed   14 times


$file = new Zend_Form_Element_File('file');
$file->setLabel('File to upload:')
    ->addValidator('Count', false, 1)


if ($form->isValid($request->getPost()) {
    $newFilename = 'foobar.txt';
    //how should I rename the file?
    //When should I rename the file? Before or after receiving?
    try {
        echo 'filename: '. $form->file->getFileName();


  1. When I call $form->file->getFileName() it returns the full path, not just the file name. How can I output just the name of the file?

    //Answer: First, get an array of the parts of the filename:
    $pathparts = pathinfo($form->file->getFileName());
    //then get the part that you want to use
    $originalFilename = $pathparts['basename'];
  2. How can I rename the filename to something I want? Can this be done with the Rename 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?

    //Answer: Use the rename filter:
    $form->file->addFilter('Rename', 'new-file-name-goes-here.txt');

Final Solution:

This is what I ended up doing:

public function foobarAction()

    if (!$form->isValid($request->getPost())) {
        $this->view->form = $form;

    //the following will rename the file (I'm setting the upload dir in the form)
    $originalFilename = pathinfo($form->file->getFileName());
    $newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension'];
    $form->file->addFilter('Rename', $newFilename);

    try {
        //upload complete!
        $file = new Default_Model_File();
    } catch (Exception $e) {
        //error: file couldn't be received, or saved (one of the two)



To answer question 1, to get a filename from a full path, you can use basename, or pathinfo.

For example (copy-paste from the doc) :

$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"

Or :

$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "n";
echo $path_parts['basename'], "n";
echo $path_parts['extension'], "n";
echo $path_parts['filename'], "n"; // since PHP 5.2.0

To rename / move the file, I suppose rename would do the trick, even if it's quite not "Zend Framework solution".

If the file has not been moved by ZF and is still in the temporary directory, you should use move_uploaded_file -- but as you are using setDestination, I suppose the file is no longer in the sytem's temporary directory.

Saturday, May 29, 2021
var file = $('#file_upload').val();

This will return only a path to file on client machine. for securit reason it is returned like c:fakepathfile_name.ext. If I remember correctly, in some older browsers it was possible to get a real path. But still, it does not helps you to get a file on server.

For ajax style upload you can use some of plugins you got recommended. Or just use jQuery Forms plugin. It will work very similar to $.ajax.

Now, when file is uploaded correctly, you will find all required info about it in $_FILES

In your case it will be something like $_FILES['file_upload'] where 'file_upload' is a name of your file input.

Now you can move it from temporary storage with move_uploaded_file. And do whatever you want with that file

EDIT: And I see you are using Zend. Take a look at this about how to work with FileUpload element on the server side. With Zend you may use FileUpload methods instead of move_uploaded_file

Saturday, May 29, 2021

Use os.rename:

import os

os.rename('a.txt', 'b.kml')
Tuesday, June 1, 2021

The problem is in this line,

File from = new File(directory, "currentFileName");

Here currentFileName is actually a String you dont have to use "

try it this way,

File from      = new File(directory, currentFileName  );
                                    ^               ^         //You dont need quotes
Thursday, June 10, 2021

Alright, so I did more digging and it turns out there may be an issue with the way I was chaining addFilter() so I decided to move in a different direction, trying to isolate each file and handle it's upload individually. So far it appears to be working. Here is the revised code:

$data['image'] = (isset($_FILES["image"]) && $_FILES["image"]["name"] ? $_FILES["image"]["name"] : NULL);
$data['file'] = (isset($_FILES["file"]) && $_FILES["file"]["name"] ? $_FILES["file"]["name"] : NULL);

$upload = new Zend_File_Transfer();

$files = $upload->getFileInfo();

$options = array('ignoreNoFile' => TRUE);

foreach ($files as $field => $contents)

 // upload instructions for image
 if ($field == 'image')
  $upload->addFilter('Rename', array('target' => RESOURCES_IMG . $data['image'], 'overwrite' => TRUE), 'image')
         ->addValidator('ImageSize', false, array('minwidth'  => 100,
                                                  'maxwidth'  => 100,
                                                  'minheight' => 100,
                                                  'maxheight' => 100), 'image')
         ->addValidator('Extension', false, 'jpg', 'image');

 // upload instructions for file
 if ($field == 'file')
  $upload->addFilter('Rename', array('target' => RESOURCES_FILES . $data['file'], 'overwrite' => TRUE), 'file');

 if(!$upload->receive($field)) {
  echo '<h1>Oops</h1><p>Please correct the following errors: <hr /></p>';

  foreach ($upload->getMessages() as $key => $val)
   echo '<p><strong>' . $key . '</strong><br />' . $val . '</p>';
} // foreach

Pseudo Explanation

I use the getFileInfo() to grab an array of the files available to me then I loop over each. At the beginning of my first for loop I check to see if this file has a name, if it doesn't have a name I assume that field was left blank and is NULL so I tell the loop to skip over that and continue.

Once I'm in the loop I'm just matching my upload directives with the appropriate form field using a simple conditional. The rest should be fairly self-explanatory if you're into Zend stuff.

Hopefully this helps someone else that was in my predicament. If you are a Zend guru maybe you can comment on my solution or fix the bug that's causing the issue. There may be a more "Zend" way of doing it, but it's working now and that feels damn good.


Why I thought it was the chaining of the addFilter() method, see the note under Example #3 (below):

Note: Note that even though setting the same filter multiple times is allowed, doing so can lead to issues when using different options for the same filter.

A random blog article that inspired me to try isolating each, I'm calling it, "upload directive" although I'm not sure if that's what it's called:

Friday, October 22, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :