Skip to content

Instantly share code, notes, and snippets.

@YakovL
Forked from somatonic/creat_zip_download.php
Last active September 12, 2021 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YakovL/a5425e7f4e116aee87fb121a3ab0b26d to your computer and use it in GitHub Desktop.
Save YakovL/a5425e7f4e116aee87fb121a3ab0b26d to your computer and use it in GitHub Desktop.
create a zip file and send to browser
<?php
// this file is supposed to be in UTF-8 without BOM
function isRunningOnWindows() {
$os = php_uname('s'); //PHP_OS see https://stackoverflow.com/q/1482260/3995261
return preg_match('#win#i',$os) ? true : false;
}
function fixFilenameEncoding($name) {
// seemingly is needed on Windows only because filename encoding is not utf-8
return isRunningOnWindows() ? mb_convert_encoding($name, "windows-1251", "utf-8") : $name;
}
function fixInZipFilenameEncoding($name) {
return isRunningOnWindows() ? iconv("cp1251", "cp866", $name) : $name;
}
//# test: presumably these fixes should be removed for PHP 7.1
$files_to_zip = fixFilenameEncoding(...); //# set or calc to your liking
$zip_name = fixFilenameEncoding(...); //# set or calc to your liking
/* creates a compressed zip file */
function create_zip($files = array(), $destination = '', $overwrite = false) {
if(file_exists($destination) && !$overwrite)
return false;
if(is_array($files)) // skip unexisting files
foreach($files as $name => $file)
if(!file_exists($file))
unset($files[$name]);
if(!count($files)) // no files actually
return false;
$zip = new ZipArchive();
if(!$zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE))
return false;
foreach($files as $name => $file) {
$encoded_file_name = fixInZipFilenameEncoding($file); // prevent zip from corrupting cyrillics
$zip->addFile($file,$encoded_file_name);
}
$zip->close();
return $destination;
}
function send_zip($name) { //# cache-preventing headers to be reviewed
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename*=UTF-8''".rawurlencode(basename($name)).";"); // see https://stackoverflow.com/q/93551/3995261
header("Content-Length: ".filesize($name));
readfile($name);
}
$zip = create_zip($files_to_zip,$zip_name,false);
if(file_exists($zip_name))
send_zip($zip_name);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment