Previous Next

Zend_File_Transfer

Zend_File_Transfer provides extensive support for file uploads and downloads. It comes with built-in validators for files plus functionality to change files with filters. Protocol adapters allow Zend_File_Transfer to expose the same API for transport protocols like HTTP, FTP, WEBDAV and more.

Note: Limitation

The current implementation of Zend_File_Transfer is limited to HTTP Post Uploads. Other adapters supporting downloads and other protocols will be added in future releases. Unimplemented methods will throw an exception. For now, you should use Zend_File_Transfer_Adapter_Http directly. As soon as there are multiple adapters available you can use a common interface.

Note: Forms

When you are using Zend_Form you should use the APIs provided by Zend_Form and not Zend_File_Transfer directly. The file transfer support in Zend_Form is implemented with Zend_File_Transfer, so the information in this chapter may be useful for advanced users of Zend_Form.

The usage of Zend_File_Transfer is relatively simple. It consists of two parts. The HTTP form does the upload, while the Zend_File_Transfer handles the uploaded files. See the following example:

Example #1 Simple Form for Uploading Files

This example illustrates basic file uploading. The first part is the file form. In our example there is one file to upload.

Choose a file to upload:

For convenience, you can use Zend_Form_Element_File instead of building the HTML manually.

The next step is to create the receiver of the upload. In our example the receiver is located at /file/upload. So next we will create the 'file' controller and the upload() action.

$adapter = new Zend_File_Transfer_Adapter_Http();

$adapter->setDestination('C:\temp');

if (!$adapter->receive()) {
    $messages = $adapter->getMessages();
    echo implode("\n", $messages);
}

This code listing demonstrates the simplest usage of Zend_File_Transfer. A local destination is set with the setDestination() method, then the receive() method is called. if there are any upload errors, an error will be returned.

Note: Attention

This example is suitable only for demonstrating the basic API of Zend_File_Transfer. You should never use this code listing in a production environment, because severe security issues may be introduced. You should always use validators to increase security.

Supported Adapters for Zend_File_Transfer

Zend_File_Transfer is designed to support a variety of adapters and transfer directions. With Zend_File_Transfer you can upload, download and even forward (upload one adapter and download with another adapter at the same time) files.

Options for Zend_File_Transfer

Zend_File_Transfer and its adapters support different options. You can set all options either by passing them to the constructor or by calling setOptions($options). getOptions() will return the options that are currently set. The following is a list of all supported options.

  • ignoreNoFile: If this option is set to TRUE, all validators will ignore files that have not been uploaded by the form. The default value is FALSE which results in an error if no files were specified.

Checking Files

Zend_File_Transfer has several methods that check for various states of the specified file. These are useful if you must process files after they have been uploaded. These methods include:

  • isValid($files = null): This method will check if the given files are valid, based on the validators that are attached to the files. If no files are specified, all files will be checked. You can call isValid() before calling receive(); in this case, receive() will not call isValid() internally again when receiving the file.

  • isUploaded($files = null): This method will check if the specified files have been uploaded by the user. This is useful when you have defined one or more optional files. When no files are specified, all files will be checked.

  • isReceived($files = null): This method will check if the given files have already been received. When no files are specified, all files will be checked.

Example #2 Checking Files

$upload = new Zend_File_Transfer();

// Returns all known internal file information
$files = $upload->getFileInfo();

foreach ($files as $file => $info) {
    // file uploaded ?
    if (!$upload->isUploaded($file)) {
        print "Why havn't you uploaded the file ?";
        continue;
    }

    // validators are ok ?
    if (!$upload->isValid($file)) {
        print "Sorry but $file is not what we wanted";
        continue;
    }
}

$upload->receive();

Additional File Informations

Zend_File_Transfer can return additional information on files. The following methods are available:

  • getFileName($file = null, $path = true): This method will return the real file name of a transferred file.

  • getFileInfo($file = null): This method will return all internal information for the given file.

  • getFileSize($file = null): This method will return the real filesize for the given file.

  • getHash($hash = 'crc32', $files = null): This method returns a hash of the content of a given transferred file.

  • getMimeType($files = null): This method returns the mimetype of a given transferred file.

getFileName() accepts the name of the element as first parameter. If no name is given, all known filenames will be returned in an array. If the file is a multifile, you will also get an array. If there is only a single file a string will be returned.

By default file names will be returned with the complete path. If you only need the file name without path, you can set the second parameter, $path, which will truncate the file path when set to FALSE.

Example #3 Getting the Filename

$upload = new Zend_File_Transfer();
$upload->receive();

// Returns the file names from all files
$names = $upload->getFileName();

// Returns the file names from the 'foo' form element
$names = $upload->getFileName('foo');

Note:

Note that the file name can change after you receive the file, because all filters will be applied once the file is received. So you should always call getFileName() after the files have been received.

getFileSize() returns per default the real filesize in SI notation which means you will get 2kB instead of 2048. If you need only the plain size set the useByteString option to FALSE.

Example #4 Getting the size of a file

$upload = new Zend_File_Transfer();
$upload->receive();

// Returns the sizes from all files as array if more than one file was uploaded
$size = $upload->getFileSize();

// Switches of the SI notation to return plain numbers
$upload->setOption(array('useByteString' => false));
$size = $upload->getFileSize();

Note: Client given filesize

Note that the filesize which is given by the client is not seen as save input. Therefor the real size of the file will be detected and returned instead of the filesize sent by the client.

getHash() accepts the name of a hash algorithm as first parameter. For a list of known algorithms refer to » PHP's hash_algos method. If you don't specify an algorithm, the crc32 algorithm will be used by default.

Example #5 Getting the hash of a file

$upload = new Zend_File_Transfer();
$upload->receive();

// Returns the hashes from all files as array if more than one file was uploaded
$hash = $upload->getHash('md5');

// Returns the hash for the 'foo' form element
$names = $upload->getHash('crc32', 'foo');

Note: Return value

Note that if the given file or form name contains more than one file, the returned value will be an array.

getMimeType() returns the mimetype of a file. If more than one file was uploaded it returns an array, otherwise a string.

Example #6 Getting the mimetype of a file

$upload = new Zend_File_Transfer();
$upload->receive();

$mime = $upload->getMimeType();

// Returns the mimetype for the 'foo' form element
$names = $upload->getMimeType('foo');

Note: Client given mimetype

Note that the mimetype which is given by the client is not seen as save input. Therefor the real mimetype of the file will be detected and returned instead of the mimetype sent by the client.

Warning

Possible exception

Note that this method uses the fileinfo extension if it is available. If this extension can not be found, it uses the mimemagic extension. When no extension was found it raises an exception.

Warning

Original data within $_FILES

Due to security reasons also the original data within $_FILES will be overridden as soon as Zend_File_Transfer is initiated. When you want to omit this behaviour and have the original data simply set the detectInfos option to FALSE at initiation.

This option will have no effect after you initiated Zend_File_Transfer.

Progress for file uploads

Zend_File_Transfer can give you the actual state of a fileupload in progress. To use this feature you need either the APC extension which is provided with most default PHP installations, or the UploadProgress extension. Both extensions are detected and used automatically. To be able to get the progress you need to meet some prerequisites.

First, you need to have either APC or UploadProgress to be enabled. Note that you can disable this feature of APC within your php.ini.

Second, you need to have the proper hidden fields added in the form which sends the files. When you use Zend_Form_Element_File this hidden fields are automatically added by Zend_Form.

When the above two points are provided then you are able to get the actual progress of the file upload by using the getProgress() method. Actually there are 2 official ways to handle this.

Using a progressbar adapter

You can use the convinient Zend_ProgressBar to get the actual progress and can display it in a simple manner to your user.

To archive this, you have to add the wished Zend_ProgressBar_Adapter to getProgress() when you are calling it the first time. For details about the right adapter to use, look into the chapter Zend_ProgressBar Standard Adapters.

Example #7 Using the progressbar adapter to retrieve the actual state

$adapter = new Zend_ProgressBar_Adapter_Console();
$upload  = Zend_File_Transfer_Adapter_Http::getProgress($adapter);

$upload = null;
while (!$upload['done']) {
    $upload = Zend_File_Transfer_Adapter_Http:getProgress($upload);
}

The complete handling is done by getProgress() for you in the background.

Using getProgress() manually

You can also work manually with getProgress() without the usage of Zend_ProgressBar.

Call getProgress() without settings. It will return you an array with several keys. They differ according to the used PHP extension. But the following keys are given independently of the extension:

  • id: The ID of this upload. This ID identifies the upload within the extension. You can set it to the value of the hidden key which identified the upload when initially calling getProgress(). Per default it is set to progress_key. You must not change the ID afterwards.

  • total: The total filesize of the uploaded files in bytes as integer.

  • current: The current uploaded filesize in bytes as integer.

  • rate: The average upload speed in bytes per second as integer.

  • done: Returns TRUE when the upload is finished and FALSE otherwise.

  • message: The actual message. Either the progress as text in the form 10kB / 200kB, or a helpful message in the case of a problem. Problems could be, that there is no upload in progress, that there was a failure while retrieving the data for the progress, or that the upload has been canceled.

  • progress: This optional key takes a instance of Zend_ProgressBar_Adapter or Zend_ProgressBar and allows to get the actual upload state within a progressbar.

  • session: This optional key takes the name of a session namespace which will be used within Zend_ProgressBar. When this key is not given it defaults to Zend_File_Transfer_Adapter_Http_ProgressBar.

All other returned keys are provided directly from the extensions and will not be checked.

The following example shows a possible manual usage:

Example #8 Manual usage of the file progress

$upload  = Zend_File_Transfer_Adapter_Http::getProgress();

while (!$upload['done']) {
    $upload = Zend_File_Transfer_Adapter_Http:getProgress($upload);
    print "\nActual progress:".$upload['message'];
    // do whatever you need
}

Note: Knowing the file to get the progress from

The above example works when your upload identified is set to 'progress_key'. When you are using another identifier within your form you must give the used identifier as first parameter to getProgress() on the initial call.

Previous Next
Introduction to Zend Framework
Overview
Installation
Learning Zend Framework
Zend Framework Quick Start
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autoloading in Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins in Zend Framework
Introduction
Using Plugins
Conclusion
Getting Started with Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Getting Started Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Understanding and Using Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Getting Started with Zend_Session, Zend_Auth, and Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Getting Started with Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Getting Started with Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Zend Framework Reference
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
SimpleCloud API: Zend_Cloud
Document Service Introduction
Queue Service Introduction
StorageService Introduction
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Json
Zend_Config_Xml
Zend_Config_Yaml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Basic usage
Previous Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_Http_UserAgent
The UserAgent Device Interface
The UserAgent Features Adapter
The WURFL UserAgent Features Adapter
The DeviceAtlas UserAgent Features Adapter
The TeraWurfl UserAgent Features Adapter
The UserAgent Storage Interface
The Session UserAgent Storage Adapter
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Ebay
Zend_Service_Ebay_Finding
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_ShortUrl
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_WindowsAzure_Storage_Blob
Zend_Service_WindowsAzure_Diagnostics_Manager
Zend_Service_WindowsAzure_Storage_Queue
Zend_Service_WindowsAzure_Storage_Table
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internals
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Zend Framework Requirements
Introduction
Zend Framework Migration Notes
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information