Skip to content

Instantly share code, notes, and snippets.

@ninetwentyfour
Last active June 5, 2022 08:40
Show Gist options
  • Save ninetwentyfour/1177068 to your computer and use it in GitHub Desktop.
Save ninetwentyfour/1177068 to your computer and use it in GitHub Desktop.
Use PHP To Zip Folders For Download - blogpost
<?php
// WARNING
// This code should NOT be used as is. It is vulnerable to path traversal. https://www.owasp.org/index.php/Path_Traversal
// You should sanitize $_GET['directtozip']
// For tips to get started see http://stackoverflow.com/questions/4205141/preventing-directory-traversal-in-php-but-allowing-paths
//Get the directory to zip
$filename_no_ext= $_GET['directtozip'];
// we deliver a zip file
header("Content-Type: archive/zip");
// filename for the browser to save the zip file
header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");
// get a tmp name for the .zip
$tmp_zip = tempnam ("tmp", "tempname") . ".zip";
//change directory so the zip file doesnt have a tree structure in it.
chdir('user_uploads/'.$_GET['directtozip']);
// zip the stuff (dir and all in there) into the tmp_zip file
exec('zip '.$tmp_zip.' *');
// calc the length of the zip. it is needed for the progress bar of the browser
$filesize = filesize($tmp_zip);
header("Content-Length: $filesize");
// deliver the zip file
$fp = fopen("$tmp_zip","r");
echo fpassthru($fp);
// clean up the tmp zip file
unlink($tmp_zip);
?>
<a href="zip_folders.php?directtozip=THE USERS DIRECTORY">Download All As Zip</a>
@vishal-yad14
Copy link

Please tell me how to write the users Directory.

@requinix
Copy link

Keep your fingers crossed that some user won't try links like

<a href="zip_folders.php?directtozip=../">Download my website as a zip file!</a>

Or even further down the directory hierarchy...

A quick check that the $filename_no_ext contains valid characters and, of course, that user_uploads/$filename_no_ext exists would remedy this problem.

@ninetwentyfour
Copy link
Author

That is a good point. I guess I never intended this to be used as is. I've update the gist and blog post with a warning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment