This documentation is for the old version. Go to the latest Upload Suite docs

Uploading Additional Data in PHP

Quite often it is necessary to send additional information along with files. Image Uploader comprehensively solves this task and supports uploading the following kinds of additional information:

  • common information about upload defined by the Web site logic, such as an author name, keywords, or a category caption
  • a simple text description
  • a hidden tag
  • image crop bounds and rotation angle
  • more image-specific information, like copyright notes and camera parameters during capturing, contained in EXIF and IPTC fields
  • hash sums

This topic has three paragraphs, namely, uploading common data, uploading image-specific data and hash sums. Each of them describes approaches on how to send and receive relevant data, possibilities provided by these approaches, and code samples.

Note

If you are unfamiliar with the Saving Uploaded Files in PHP topic, please, read it first.

Uploading Common Data

This section describes several approaches to uploading additional data. They are quite different but have two features in common, namely, independence of file types and upload of common data.

  • To get user-provided information about a whole upload you may use an HTML form, as it is described in the using additional HTML form section. This approach is simple to use and understand, it is also quite flexible. Pay attention to the fact that in this case you cannot upload different data for different files, only one set of data for a whole upload.
  • To add hidden data to a whole upload you can use custom fields. As opposed to the previous method, this one allows you to add data programmatically. For more information about this approach, see the using additional field section.
  • To upload user-defined file descriptions you do not need to configure Image Uploader beforehand, so it is the simplest way to get additional information with each uploaded file. Receiving of descriptions is examined in the using descriptions section.
  • To send a hidden piece of data for each user-selected file you may use tags. This approach is described in the using tags section.
  • To add elementary information to upload you can pass additional data as arguments like it is usually done in GET requests, this approach is described in the using query string section.

Using Additional HTML Form

Using HTML forms is the most straight-forward way to upload data in web applications, thus Image Uploader supports it. All you need is just to add the desired form to the same page where the Uploader class instance is hosted and set the Metadata.AdditionalFormName property to the name of created form. Then, when a user clicks Upload, the form data will be submitted along with user-selected files. On the server side, the fields of this form are accessible through the Package.PackageFields collection by their names.

An additional form can contain HTML input elements of different types, for example, you may use:

  • text for author's name
  • checkbox to determine whether to send a notification about the upload completion or not
  • select to choose keywords related to the upload
Note

The following input types are not allowed: file, image, button, and reset. Their values will not be sent at all.

Sending Data

The following configuration makes Image Uploader sending data from the addForm form along with uploaded files.

PHP
<form id="addForm" name="addForm">
    <input ID="keywords" name="keywords" type="text" />
    <input ID="addressee" name="addressee" type="text" />
</form>

<?php
    require_once "ImageUploaderPHP/Uploader.class.php";
    
    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php");
    $uploader->getMetadata()->setAdditionalFormName("addForm");
    $uploader->render();
?>

Receiving Sent Data

Fields of the additional form are sent in each package, though in the following example we use package containing the first file, which number is 0, because there is always at least one file in the upload session.

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveAllUploadedFiles($uploadedFiles) {
    $packageFields = $uploadedFiles[0]->getPackage()->getPackageFields();
    $keywords = $packageFields["keywords"];
    $addressee = $packageFields["addressee"];
}

$handler = new UploadHandler();
$handler->setAllFilesUploadedCallback("saveAllUploadedFiles");
$handler->processRequest();

Using Additional Field

Additional fields can be attached to the POST request using the metadata.addCustomField(String, String, Boolean) method. It accepts the following parameters:

  1. name of the additional field
  2. value of the additional field
  3. optional parameter telling how to deal with previous value of this field, which is overwritten by default

You may add custom fields to the upload request only at runtime using the Image Uploader JavaScript API. Custom fields can use any format you like but should not conflict with the standard field names. See the POST Field Reference topic for a full list of standard Image Uploader fields.

On the server side, additional fields are accessible through the Package.PackageFields collection by their names.

The following example sends and receives an additional field named authorField. Here the metadata.addCustomField(String, String, Boolean) method is called in the BeforeUpload event handler, which fires when the upload is about to be started. For more information about events, please, see the using events section.

Sending Data

PHP
<script type="text/javascript">
function onBeforeUpload() {
    $au.uploader('Uploader1').metadata().addCustomField('authorField', 'Author Name');
}
</script>
<?php
    require_once "ImageUploaderPHP/Uploader.class.php";
    
    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php");
    $uploader->getClientEvents()->setBeforeUpload("onBeforeUpload");
    $uploader->render();
?>

Receiving Sent Data

Additional fields are sent in each package, though in the following example we use package containing the first file, which number is 0, because there is always at least one file in the upload session.

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveAllUploadedFiles($uploadedFiles) {
    $packageFields = $uploadedFiles[0]->getPackage()->getPackageFields();
    $author = $packageFields["authorField"];
}

$handler = new UploadHandler();
$handler->setAllFilesUploadedCallback("saveAllUploadedFiles");
$handler->processRequest();

Receiving Descriptions

Each file uploaded via Image Uploader may have a description. There is no need to turn this possibility on, because it is enabled by default. So, let us examine how to get descriptions of uploaded files on a server using the callback function specified by the UploadHandler.FileUploadedCallback property:

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveUploadedFile($uploadedFile) {
    $description = $uploadedFile->getDescription();
}

$handler = new UploadHandler();
$handler->setFileUploadedCallback("saveUploadedFile");
$handler->processRequest();

Using Tags

Tags give you an opportunity to send a hidden piece of data with each user-selected file. To attach such data use the file.tag property as it is demonstrated in the sample below. You may set tags only at runtime using the Image Uploader JavaScript API.

On the server side you may get a tag through the UploadedFile.Tag property.

The following example sends and receives tags for all selected files. Here the file.tag property is specified in the BeforeUpload event handler, which fires when the upload is about to be started. For more information about events, please, see the using events section.

Sending Data

PHP
<script type="text/javascript">
function onBeforeUpload() {
    var files = $au.uploader('Uploader1').files();
    var count = files.count();
    for (var i = 0; i < count; i++) 
        files.get(i).tag('tag;file_' + i);
}
</script> 
<?php
    require_once "ImageUploaderPHP/Uploader.class.php";
    
    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php");
    $converters = &$uploader->getConverters();
    $converter = new Converter();
    $converter->setMode("*.*=SourceFile");
    $converters[] = $converter;
    $uploader->getClientEvents()->setBeforeUpload("onBeforeUpload");
    $uploader->render();
?>

Receiving Sent Data

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveUploadedFile($uploadedFile) {
    $tag = $uploadedFile->getTag();
}

$handler = new UploadHandler();
$handler->setFileUploadedCallback("saveUploadedFile");
$handler->processRequest();

Using Query String

To pass data via the query string, just add necessary arguments to the upload script URL (UploadSettings.ActionUrl) and parse the request on a server as it is shown in the example below.

Sending Data

PHP
<?php
    require_once "ImageUploaderPHP/Uploader.class.php";
    
    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php?argument1=value1&argument2=value2");
    $uploader->render();
?>

Receiving Sent Data

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveAllUploadedFiles($uploadedFiles) {
    $argument1 = $_GET["argument1"];
    $argument2 = $_GET["argument2"];
}

$handler = new UploadHandler();
$handler->setAllFilesUploadedCallback("saveAllUploadedFiles");
$handler->processRequest();

Uploading Image-specific Data

Image Uploader has some imaging capabilities, which are described in the Working with Images topic and Uploading Images section. Let us describe two of these features, which allow uploading additional data:

  1. Rotating and Cropping of images are enabled in Image Uploader by default. So, it is a good idea to get rotation angle and crop bounds on a server. To know more on how to do this, see the receiving rotation angle and crop bounds section.
  2. Working with EXIF and IPTC Metadata provides, among other possibilities, an opportunity to extract and upload EXIF and IPTC fields for each user-selected image. EXIF metadata is a special information about the image, written into the file by the capturing device when an image was captured. These metadata may provide camera parameters during capturing, date and time of the capturing, photographer's name, and etc. IPTC is another metadata format, which is widely used in journalism to keep information about a photo, like byline, subject, location, and etc. See the handling EXIF and IPTC metadata section for detailed description on how to send and receive such metadata.

Receiving Rotation Angle and Crop Bounds

A rotation angle and crop bounds can be got through the Angle and CropBounds properties of the UploadedFile class respectively. Image Uploader measures rotation angle in degrees clockwise.

As soon as rotation and cropping of images are allowed by default, there is no need to configure Image Uploader to send them, so the following example shows only how to receive such data on a server.

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveUploadedFile($uploadedFile) {
    $angle = $uploadedFile->getAngle();
    $cropBounds = $uploadedFile->getCropBounds();
}

$handler = new UploadHandler();
$handler->setFileUploadedCallback("saveUploadedFile");
$handler->processRequest();

Handling EXIF and IPTC Metadata

To upload EXIF or IPTC values, you should specify the desired fields using the Metadata.Exif and Metadata.Iptc properties. Both these properties represent semicolon separated lists of field names which should be extracted and uploaded along with images. To specify a custom EXIF tag, for example, Windows image title, use the hexadecimal ID of the tag. Metadata.ValueSeparator sets a string separator for fields which can contain multiple string values, like IptcKeyword.

Sending Data

The following example sends two EXIF and two IPTC fields for each user-selected image:

PHP
<?php
    require_once "ImageUploaderPHP/Uploader.class.php";
    
    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php");
    $converters = &$uploader->getConverters();
    $converter = new Converter();
    $converter->setMode("*.*=SourceFile");
    $converters[] = $converter;
    $uploader->getMetadata()->setIptc("IptcCopyrightNotice;IptcKeyword");
    //here 0x9c9b is the hexadecimal ID of the windows image title tag
    $uploader->getMetadata()->setExif("ExifColorSpace;ExifDateTime;0x9c9b");
    $uploader->getMetadata()->setValueSeparator(";");
    $uploader->render();
?>

Receiving Sent Data

The following example gets the EXIF and IPTC fields sent accordingly to the previous configuration and writes these values to the Descriptions.xml file. Here uploaded fields are contained in the Package.PackageFields collection and can be retrieved by keys named in the following way: FieldName_xx, where FieldName is a name of an EXIF or IPTC field and xx is the index of an uploaded file in this package. To get access to a custom EXIF tag use the ExifCustom_ID_xx keys, where ID is tag's hexadecimal ID.

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveUploadedFile($uploadedFile) {
    $absGalleryPath = realpath("Gallery/");
    $packageFields = $uploadedFile->getPackage()->getPackageFields();
    
    $descriptions = new DOMDocument('1.0');
    if (file_exists($absGalleryPath . "/Descriptions.xml"))
        $descriptions->load($absGalleryPath . "/Descriptions.xml");
    else
        $descriptions->appendChild($descriptions->createElement("files"));
    
    $xmlFile = $descriptions->createElement("file");
    $xmlFile->setAttribute("name",  $uploadedFile->getSourceName());
    $xmlFile->setAttribute("CopyrightNotice", $packageFields["IptcCopyrightNotice_" . $uploadedFile->getIndex()]);
    $xmlFile->setAttribute("IptcKeyword", $packageFields["IptcKeyword_" . $uploadedFile->getIndex()]);
    $xmlFile->setAttribute("ExifColorSpace", $packageFields["ExifColorSpace_" . $uploadedFile->getIndex()]);
    $xmlFile->setAttribute("ExifDateTime", $packageFields["ExifDateTime_" . $uploadedFile->getIndex()]);
    //here 9C9B is the hexadecimal ID of the windows image title tag
    $xmlFile->setAttribute("Windows title", $packageFields["ExifCustom_9C9B_" . $uploadedFile->getIndex()]);
    $descriptions->documentElement->appendChild($xmlFile);
    $descriptions->save($absGalleryPath . "/Descriptions.xml");
}

$handler = new UploadHandler();
$handler->setFileUploadedCallback("saveUploadedFile");
$handler->processRequest();
Note

All date/time values have the following format: YYYY:MM:DD hh:mm:ss. For example, May 11, 2006, 2:40PM would be represented as: 2006:05:11 14:40:00.

Using Hash Sums

Note

Image Uploader Express does not support creating hash sums for files. See the Comparison of Image Uploader Editions topic for details.

File hash sum uniqely identifies a file; it is useful for accomplishing two main tasks: to check uploaded files integrity and to prevent duplicate file upload.

Image Uploader provides the Converter.Hash and Metadata.Hash properties to enable hash sums. The Converter.Hash property is used to enable hash values for checking upload integrity. If you use this property, Image Uploader will send hash value for a converted file along with the file. The Metadata.Hash property allows sending hash sums without sending files; it is useful to prevent duplicate files upload.

On the server side uploaded hash sums are accessible through the Package.PackageFields collection. Image Uploader encodes hash values using the Base64 algorithm; make sure that the server-side script uses the same algorithm. To send several hash values (calculated using different algorithms) specify the semicolon-separated list of algorithms as a property value.

Checking Upload Integrity

Checking upload integrity works in the following way:

  1. You set one or several hash algorithms using the Converter.Hash property.
  2. Before the upload process begins, Image Uploader calculates the hash value (or several values) according to settings specified on the first step.
  3. Base64-encoded hash values are appended to the request.
  4. The server-side code calculates hash values for received files using the algorithm specified on the first step and compares values with the ones received from the client side.
  5. If hash values are the same, the verification is successful. Otherwise, the upload is corrupted.

On the server side you can receive hash values using the following field name: FileNAlgorithmName_xx, where AlgorithmName is the name of hash algorithm (SHA, MD2, or MD5), N is a zero-based index of the converter, and xx is the index of an uploaded file in a package.

In the following two-part example Image Uploader sends an MD5 hash sum for each created thumbnail. The server-side script in the second part calculates MD5 hash value for received thumbnail, compares it with the uploaded sum, and saves the file if both hash sums are identical, which means that upload is successful.

Sending Data

PHP
<?php
    require_once "ImageUploaderPHP/Uploader.class.php";

    $uploader = new Uploader("Uploader1");
    $uploader->getUploadSettings()->setActionUrl("upload.php");
    $converters = &$uploader->getConverters();
    $converter = new Converter();
    $converter->setMode("*.*=Thumbnail");
    $converter->setHash("MD5");
    $converters[] = $converter;
    $uploader->render();
?>

Receiving Sent Data

PHP
require_once "ImageUploaderPHP/UploadHandler.class.php";
function saveUploadedFile($uploadedFile) {
    $absGalleryPath = realpath("Gallery/");
    $packageFields = $uploadedFile->getPackage()->getPackageFields();
    
    $convertedFiles = $uploadedFile->getConvertedFiles();
    $md5Hash = base64_encode(md5($convertedFiles[0]->getFileContent(), true));
    if ($md5Hash == $packageFields["File0MD5_" . $uploadedFile->getIndex()])
        $convertedFiles[0]->moveTo(realpath("Gallery/") . DIRECTORY_SEPARATOR . $convertedFiles[0]->getName());
    
}

$handler = new UploadHandler();
$handler->setFileUploadedCallback("saveUploadedFile");
$handler->processRequest();

Preventing Duplicate File Upload

Using the Metadata.Hash property you can detect duplicate files before they are uploaded to the server. The idea is to upload hash values for all user-selected files on the first step, then check whether these files have already been uploaded to the Web server in the past or not, and upload only the files not exisitng on the server. In general, the following actions should be implemented:

  1. You configure Image Uploader to send hash values without sending the files: use the Metadata.Hash property to specify desired hash algorithm and set the Converter.Mode property to "*.*=None".
  2. After upload starts, Image Uploader uploads hash values.
  3. Server script checks for duplicates by comparing newly uploaded hash values with the ones already stored on the server.
  4. If there are duplicates, server script sends a response containing list of duplicate files.
  5. The Uploader.AfterUpload event handler deletes duplicate files from the upload list and initiates files upload process (by calling the uploader.upload() method).
  6. The BeforeUpload event handler sets the Converter.Mode property to "*.*=SourceFile" to enable sending original files.
  7. Image Uploader sends unique files to the server.
Note

You can detect duplicates of original files only; not thumbnails.

On the server side you can receive hash values using the following field name: HashCodeAlgorithmName_xx, where AlgorithmName is one of the following algorithms: SHA, MD2, or MD5 and xx is the index of an uploaded file in a package.

The following two-part example illustrates this approach. The first part configures Image Uploader, controls upload process, and deletes duplicate files from upload list (if any). The server-side script in the second part compares received hash values with the stored ones, sends back list of duplicate files (if any), and saves uploaded files and their hash values to file system. The example stores hash values in XML file solely for brevity; in a real-life application most likely you will use database instead.

Sending Data

PHP
<script type="text/javascript">
var redirectUrl = 'gallery.php',
uploadCompletedMessage = '';

function onBeforeUpload() {
    if (this.converters().get(0).mode() == '*.*=None') {
        // Upload hashes only
        this.uploadPane().saveUploadList(1);
        this.metadata().addCustomField('hashcheck', '1');
        this.uploadSettings().redirectUrl('');
        uploadCompletedMessage = this.messages().uploadCompleted();
        this.messages().uploadCompleted('');
    } else {
        this.uploadPane().resetUploadList(1);
        this.metadata().removeCustomField('hashcheck');
        this.uploadSettings().redirectUrl(redirectUrl);
        this.messages().uploadCompleted(uploadCompletedMessage);
    }
}

function onAfterUpload(data) {
    if (this.converters().get(0).mode() == '*.*=None') {
        this.converters([{ mode: '*.*=SourceFile' }]);
        this.uploadPane().loadUploadList(1);
        if (data) {
            var indexes = data.split(';');
            // Remove duplicates from upload list
            for (var i = indexes.length - 1; i >= 0; i--) 
                this.files().remove(parseInt(indexes[i], 10));
        }
        if (this.files().count() > 0) {
            // Upload files
            var u = this;
            setTimeout(function() {u.upload();}, 100);
        }
    }
}

</script>

<?php
    require_once 'ImageUploaderPHP/Uploader.class.php';
    
    $uploader = new Uploader('Uploader1');
    $uploader->getUploadSettings()->setActionUrl('upload.php');
    
    $converters = &$uploader->getConverters();
    $converter = new Converter();
    $converter->setMode("*.*=None");
    $converters[] = $converter;
    
    $uploader->getMetadata()->setHash('MD5');
    
    $uploader->getClientEvents()->setAfterUpload('onAfterUpload');
    $uploader->getClientEvents()->setBeforeUpload('onBeforeUpload');
    
    $uploader->render();
?>

Receiving Sent Data

PHP
require_once 'ImageUploaderPHP/UploadHandler.class.php';
 
$galleryPath = 'Gallery/';
 
function onAllFilesUploaded($uploadedFiles) {
    global $galleryPath;
    $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
    
    if (!empty($_POST['hashcheck'])) {
        $hashes = array();
        foreach ($uploadedFiles as $uploadedFile) {
                $hash = $uploadedFile->getPackage()->getPackageField('HashCodeMD5_' . $uploadedFile->getIndex());
                if (!empty($hash))
                    $hashes[$hash] = $uploadedFile->getIndex();
        }
            
        if (count($hashes) > 0 && file_exists($absGalleryPath . 'files.xml')) {
            $descriptions = new DOMDocument('1.0', 'utf-8');
            $descriptions->load($absGalleryPath . 'files.xml');
            
            $duplicates = array();
            for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) {
                $hash = $descriptions->documentElement->childNodes->item($i)->getAttribute('md5');
                if (array_key_exists($hash, $hashes)) 
                    $duplicates[] = $hashes[$hash];
            }
            
            if (!empty($duplicates)) {
                $duplicates = array_unique($duplicates, SORT_NUMERIC);
                sort($duplicates);
                echo implode(';', $duplicates);
            }
        }
            
        exit();
    }
    
    $descriptions = new DOMDocument('1.0', 'utf-8');
    
    if (file_exists($absGalleryPath . '/' . 'files.xml'))
        $descriptions->load($absGalleryPath . 'files.xml');
    else
        $descriptions->appendChild($descriptions->createElement("files"));
    
    foreach ($uploadedFiles as $uploadedFile) {
        $originalFileName = $uploadedFile->getSourceName();
        $files = $uploadedFile->getConvertedFiles();
        $sourceFile = $files[0];
        $sourceFile->moveTo($absGalleryPath . $originalFileName);
        
        $xmlFile = $descriptions->createElement('file');
        $xmlFile->setAttribute('name', $originalFileName);
        $xmlFile->setAttribute('md5', $uploadedFile->getPackage()->getPackageField('HashCodeMD5_' . $uploadedFile->getIndex()));
        $descriptions->documentElement->appendChild($xmlFile);
    }
    
    $descriptions->save($absGalleryPath . 'files.xml');
}
 
$handler = new UploadHandler();
$handler->setAllFilesUploadedCallback('onAllFilesUploaded');
$handler->processRequest();

See Also

Reference

Manual