Skip to content

Instantly share code, notes, and snippets.

@trangsihung
Created October 10, 2016 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trangsihung/57d97c84b72e74801b74f3d5b5ec6893 to your computer and use it in GitHub Desktop.
Save trangsihung/57d97c84b72e74801b74f3d5b5ec6893 to your computer and use it in GitHub Desktop.
PHP Scritps
<?php
$dir = 'uploads';
$zip_file = 'uploads.zip';
// Get real path for our folder
$rootPath = realpath($dir);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment