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
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");
}
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);
}
Download the file contents (possibly with file_get_contents
, or copy
to put it on your filesystem) then apply the unzip algorithm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With