views:

56

answers:

1

Hi, I'm trying to download images to a ZipArchive, from a social networking site via their API, I'm using the following code:

...
public function downloadAlbumZip($album_name, $photos)
{
    $zip = new ZipArchive();
    $album_name = $this->_cleanAlbumName($album_name);
    $filename = 'album.zip';
    $file = tempnam(PHOTOS, "{$album_name}-").'.zip';

    if ($zip->open($file, ZIPARCHIVE::CREATE) === TRUE)
    {
        foreach ($photos as $photo) {
            $image = $photo['pid'] . '.jpg';
            $binary = $this->_getImage($photo['src']);
            $zip->addFromString($image, $binary);
        }

        $output = print_r($zip, true);
        $zip->close();

        exit('Zip Saved.<br /><a href="javascript:history.go(-1);">Back to Album Overview</a>');
    } else {
        die('Zip Failed.');
    }
}

private function _getImage($img)
{
    if ( function_exists('curl_init') )
    {
        $ch = curl_init($img);

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

        $rawdata = curl_exec($ch);
        curl_close($ch);

        return $rawdata;
    }
}
...

Which works but is very slow and often ends in a timeout error, can anyone recommend a way to speed this up?

Thanks

A: 

You should download all the images first, verify that they are okay, then re-download on timeout.

You can speed images downloading by doing them in parallel using CURL_MULTI_EXEC.

Remember, the key to speeding up anything is to identify where the bottleneck is. Is it zipping the files? You could use a native binary and shell out if that is the case. Is it downloading the images? Is it the size of the images?

You should do some profiling, even if it is just echoing time() to see which operations are taking the longest.

Byron Whitlock