Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Zip file from URL with PHP

Tags:

php

I'm searching for a good solution to read a zip file from an url with php.

I checked the zip_open() function, but i never read anything about reading the file from another server.

Thank you very much

like image 730
Sandor Farkas Avatar asked Mar 15 '11 10:03

Sandor Farkas


3 Answers

The best way to do that is to copy the remote file in a temporary one:

$file = 'http://remote/url/file.zip';
$newfile = 'tmp_file.zip';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}

Then, you can do whatever you want with the temporary file:

 $zip = new ZipArchive();
 if ($zip->open($newFile, ZIPARCHIVE::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
 }
like image 87
Zakaria Avatar answered Oct 07 '22 01:10

Zakaria


This is a basic example:

$url = 'https://my.domain.com/some_zip.zip?blah=1&hah=2';
$destination_dir = '/path/to/local/storage/directory/';
if (!is_dir($destination_dir)) {
    mkdir($destination_dir, 0755, true);
}
$local_zip_file = basename(parse_url($url, PHP_URL_PATH)); // Will return only 'some_zip.zip'
if (!copy($url, $destination_dir . $local_zip_file)) {
    die('Failed to copy Zip from ' . $url . ' to ' . ($destination_dir . $local_zip_file));
}
$zip = new ZipArchive();
if ($zip->open($destination_dir . $local_zip_file)) {
    for ($i = 0; $i < $zip->numFiles; $i++) {
        if ($zip->extractTo($destination_dir, array($zip->getNameIndex($i)))) {
            echo 'File extracted to ' . $destination_dir . $zip->getNameIndex($i);
        }
    }
    $zip->close();
    // Clear zip from local storage:
    unlink($destination_dir . $local_zip_file);
}
like image 27
Vlado Avatar answered Oct 07 '22 02:10

Vlado


Download the file contents (possibly with file_get_contents, or copy to put it on your filesystem) then apply the unzip algorithm.

like image 35
Lightness Races in Orbit Avatar answered Oct 07 '22 01:10

Lightness Races in Orbit