## Aurigma Image Uploader 6.1 Dual

# Writing Client-Side Script and Handling Upload using Image Uploader PHP

- Collapse All Sections
- See Also
- Language Filter ( all languages )

This topic supplements the Configuring Image Uploader PHP article and discusses the aspects of Image Uploader PHP library usage related to handling client-side events and receiving uploaded files server-side.

## Handling Client-Side Events

The ImageUploader class of the PHP library implements client-side event handling functionality. It allows adding and removing handlers for all Image Uploader events. These events are fired by ActiveX control or Java applet directly and handled using JavaScript. They allow you to trace all interactions between a user and the control beginning from initialization and ending by upload completion. To add a client-side event handler you should write it in JavaScript and pass its name to the corresponding method.

### PHP

    <script type="text/javascript">
        function beforeUploadHandler(){
            alert("BeforeUpload");
        }
    </script>

    <?php
        $imageUploader = new ImageUploader("ImageUploader1", 650, 400);

        $imageUploader->addClientBeforeUpload("beforeUploadHandler");

        $imageUploader->render();
    ?>

See a full list of Image Uploader events in Image Uploader API reference. However, the PHP library provides a possibility to handle two additional client-side events.

### ClientFullPageLoad

This event is raised right after Image Uploader is completely initialized and all other page elements are loaded. Despite the similarity of this event to the window.onload event, window.onload does not guarantee that by the moment when it is fired Image Uploader will be initialized. See the code sample below, it demonstrates how to restore the upload list on page load.

### PHP

    <script type="text/javascript">
        function fullPageLoadHandler(){
            getImageUploader("ImageUploader1").LoadUploadList(1);
        }
    </script>

    <?php
        $imageUploader = new ImageUploader("ImageUploader1", 650, 400);

        $imageUploader->addClientFullPageLoad("fullPageLoadHandler");

        $imageUploader->render();
    ?>

### ClientInitWriter

This event is raised just before initialization of Image Uploader. It accepts the ImageUploaderWriter object and allows modifying it before ActiveX control or Java applet is instantiated. The code snippet below shows how to change the control layout using this event handler.

### PHP

    <script type="text/javascript">
        function initWriterHandler(writer){
            writer.addParam("PaneLayout", "OnePane");
        }
    </script>

    <?php
        $imageUploader = new ImageUploader("ImageUploader1", 650, 400);

        $imageUploader->addClientInitWriter("initWriterHandler");

        $imageUploader->render();
    ?>

## Writing Server-Side Upload Script

Image Uploader PHP library includes several classes which simplify writing of upload processing script. They receive the data sent by Image Uploader (ActiveX control or Java applet) as a POST request, parse it, and provide a typed access to this data server-side. Here we will consider primary aspects of receiving and working with uploaded data.

### Getting Uploaded Data

The uploaded data can be retrieved using the UploadedFiles class defined in the UploadedFiles.php file of the PHP library. This class represents uploaded files as an array and provides methods to access its elements. The UploadedFiles::getAll() method returns the whole array and the UploadedFiles::fetchNext() method iterates through it.

Note

The UploadedFiles array is empty if the user aborts uploading. So you do not need to apply request integrity checking before saving uploaded file. If, however, you want to know whether the user cancels the upload use the UploadedFiles::isRequestCompletelyReceived() method.

Each element of the UploadedFiles array is the UploadedFile object which provides an access to the uploaded file itself and additional data through its methods:

- getSourceFile() returns a source file.
- getThumbnail($index) returns a thumbnail by specified index.
- getDescription() returns user-specified description.
- getExif($key) and getIptc($key) return EXIF and IPTC metadata fields by specified keys.
- and others.

See a full list of UploadedFile methods in Image Uploader PHP library reference.

The code snippet below demonstrates how to iterate through uploaded files.

### PHP

    <?php
        while (($uploadedFile = UploadedFiles::fetchNext()) != null){

            //Your  code

        }
    ?>

### Getting Source File

In the case if Image Uploader is configured to send source files (the setUploadSourceFile($value) property is true) you can retrieve these files using the UploadedFile::getSourceFile() method. It returns the SourceFileInfo class instance. This class has a number of methods which provide an access to characteristics of the uploaded file and allow saving it on a server. The most useful ones are listed below:

- getFileName() and getFileSize() return name and size of the original file respectively.
- getWidth() and getHeight() return image dimensions in pixels.
- getHorizontalResolution() and getVerticalResolution() return horizontal and vertical image resolutions in dpi.
- save($filename) saves a source file to specified path on a server.
- saveToFolder($dirPath, $renameConflicted) saves a source file to the specified directory on a server avoiding name conflict.

Here is a short code snippet which shows how to use the SourceFileInfo class to save a source file on a server and write some file-related information (filename, image dimensions, and user description) to a XML file.

### PHP

    <?php
        $galleryPath = "Gallery/";

        $descriptions = new DOMDocument("1.0");
        $descriptions->appendChild($descriptions->createElement("files"));

        while (($uploadedFile = UploadedFiles::fetchNext()) != null){

            $sourceFile = $uploadedFile->getSourceFile();
            $sourceFileName = $sourceFile->getFileName();

            $descriptionsFile = $descriptions->createElement("file");
            $descriptionsFile->setAttribute("name", $sourceFileName);
            $descriptionsFile->setAttribute("width", $sourceFile->getWidth());
            $descriptionsFile->setAttribute("height", $sourceFile->getHeight());
            $descriptionsFile->setAttribute("description", $uploadedFile->getDescription());
            $descriptions->documentElement->appendChild($descriptionsFile);

            $sourceFile->save($galleryPath. "/" .$sourceFileName);
        }

        $descriptions->save("Descriptions.xml");
    ?>

### Getting Thumbnails

By default Image Uploader sends an original image only, however, it can be configured to send downsized, rotated and watermarked copies of this image. See the detailed information about image operations in the Resizing and Rotating Images topic. Here we will consider how to adjust Image Uploader to create thumbnails and retrieve them on a server using Image Uploader PHP library.

Image Uploader PHP library allows configuring up to three thumbnails. To specify whether Image Uploader should send the first, second or third thumbnail just set the setUploadThumbnail1FitMode($value), setUploadThumbnail2FitMode($value) or setUploadThumbnail3FitMode($value) properties correspondingly to non-Off value. All other thumbnail parameters are optional, they specify such characteristics as thumbnail width and height, resize quality, etc. Use the settings below to upload the first thumbnail resized to 120x120 pixels preserving original image proportions, and the third thumbnail which size is equal to the original image.

### PHP

    <?php
        $imageUploader = new ImageUploader("ImageUploader1", 650, 400);

        $imageUploader->setUploadThumbnail1FitMode("Fit");
        $imageUploader->setUploadThumbnail1Width(120);
        $imageUploader->setUploadThumbnail1Height(120);
        $imageUploader->setUploadThumbnail3FitMode("ActualSize");

        $imageUploader->render();
    ?>

When thumbnails are uploaded they can be retrieved on a server using the UploadedFile::getThumbnail($index) method, which returns a thumbnail with the specified index. This thumbnail is represented by an instance of the ThumbnailInfo class. This class provides an access to thumbnail details (e.g. thumbnail dimensions, compression mode, etc.) and allows saving thumbnails on a server. To do it you can use the save($filename) or saveToFolder($dirPath, $renameConflicted) method analogous to similar methods of the SourceFileInfo class.

Here is the code sample which demonstrates how to retrieve the first and the third thumbnails on the server-side if they were configured as it is shown in the code snippet above.

### PHP

    <?php
        $galleryPath = "Gallery/";
        $thumbnailsPath = $galleryPath. "Thumbnails/";

        while (($uploadedFile = UploadedFiles::fetchNext()) != null){

            $sourceFile = $uploadedFile->getSourceFile();
            $sourceFileName = $sourceFile->getFileName();

            $thumbnail1 = $uploadedFile->getThumbnail(1);
            $thumbnail1->save($thumbnailsPath. "/" .$sourceFileName. "_" .$thumbnail1->getWidth().
                "x" .$thumbnail1->getHeight(). ".jpg");

            $thumbnail3 = $uploadedFile->getThumbnail(3);
            $thumbnail3->save($thumbnailsPath. "/" .$sourceFileName. "_" .$thumbnail3->getWidth().
                "x" .$thumbnail3->getHeight(). ".jpg");
        }
    ?>

### Getting Metadata

Some image file formats allow storing not only an image itself, but also some additional information about it. This data is called metadata and can be written by digital cameras or some specific software and stores capturing parameters or journalistic details. See the detailed information about supported metadata types in the Working with EXIF and IPTC Metadata topic. Here we will consider how to retrieve metadata fields server-side using Image Uploader PHP library.

To configure Image Uploader to exctract and send EXIF and IPTC details use the setExtractExif($value) and setExtractIptc($value) properties. They both accept a string which contains necessary EXIF or IPTC field names, separated with semicolons. The specified fields will be sent to the server along with the image they were extracted from, its thumbnails and other details. To access them server-side use UploadedFile::getExif($key) and UploadedFile::getIptc($key) methods respectively. Suppose that you configured the control to send some EXIF and IPTC fields like this:

### PHP

    <?php
        $imageUploader = new ImageUploader("ImageUploader1", 650, 400);

        $imageUploader->setExtractExif("ExifDateTime;ExifOrientation;ExifModel");
        $imageUploader->setExtractIptc("IptcCredit;IptcHeadline");

        $imageUploader->render();
    ?>

You can retrieve these fields on a server using the code snippet below.

### PHP

    <?php
        $xml = new DOMDocument("1.0");
        $xmlMetadata = $xml->createElement("metadata");

        while (($uploadedFile = UploadedFiles::fetchNext()) != null){

            $xmlFile = $xml->createElement("file");
            $xmlFile->setAttribute("name", $sourceFileName);

            $xmlExif = $xml->createElement("exif");
            $xmlExif->setAttribute("DateTime", $uploadedFile->getExif("ExifDateTime"));
            $xmlExif->setAttribute("Orientation", $uploadedFile->getExif("ExifOrientation"));
            $xmlExif->setAttribute("Model", $uploadedFile->getExif("ExifModel"));
            $xmlFile->appendChild($xmlExif);

            $xmlIptc = $xml->createElement("iptc");
            $xmlIptc->setAttribute("Credit", $uploadedFile->getIptc("IptcCredit"));
            $xmlIptc->setAttribute("Headline", $uploadedFile->getIptc("IptcHeadline"));
            $xmlFile->appendChild($xmlIptc);

            $xmlMetadata->appendChild($xmlFile);
        }

        $xml->appendChild($xmlMetadata);
        $xml->save("Metadata.xml");
    ?>

### Recovering Folder Structure on Server

When uploading folders you may need to preserve a folder structure on the server. This task is comprehensively discussed in the Uploading Folders topic. It shows how to configure Image Uploader to send paths along with files and how to handle them server-side. To solve this task using Image Uploader PHP library you should follow these instructions with only one difference. You should use the SourceFileInfo::getRelativeFilePath() property to retrieve a relative path instead of the FileName_i POST field. This property contains non-empty value if the folder upload feature is enabled (i.e. the AllowFolderUpload is true) and the uploaded file was located inside a subfolder. If so this property represents a relative path to the file and the SourceFileInfo::getFileName() represents its filename. For example, if the user sends a My Documents\My Photos\00001.jpg file its FileName_i POST field will contain My Documents\My Photos\00001.jpg value. However, the SourceFileInfo::getRelativeFilePath() property will contain My Documents\My Photos\ value and the SourceFileInfo::getFileName() property will contain 00001.jpg.

## See Also

### Reference

- ImageUploaderWriter Reference
- Image Uploader PHP Library Reference

### Manual

- Inserting Image Uploader PHP into Page
- Configuring Image Uploader PHP
- Resizing and Rotating Images
- Working with EXIF and IPTC Metadata
- Uploading Folders