Last active
January 31, 2017 10:00
-
-
Save Vyygir/6153d2f8205c921359eb9ed59f5d9f7a to your computer and use it in GitHub Desktop.
A function that hooks into WordPress and, when a $_GET request with a key of "download" and a value that contains a Base64 encoded array of semi-colon separated file URLS is passed, generates the ZIP on the fly and downloads it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action('wp', 'handle_all_file_downloads'); | |
function handle_all_file_downloads() { | |
if (isset($_GET) && isset($_GET['download'])) { | |
$urls = base64_decode($_GET['download']); | |
if ($urls) { | |
$urls = (strpos($urls, ';') !== false) ? explode(';', $urls) : array($urls); | |
$path = wp_upload_dir(); | |
$zip = new ZipArchive(); | |
$zip_name = uniqid('dwwindsor-download-'); | |
$zip_path = $path['basedir'] . '/' . $zip_name . '.zip'; | |
if (file_exists($zip_path)) { | |
unlink($zip_path); | |
} | |
if ($zip->open($zip_path, ZIPARCHIVE::CREATE) === true) { | |
$zip->addEmptyDir($zip_name); | |
foreach ($urls as $url) { | |
$parameters = explode('/', $url); | |
$zip->addFromString($zip_name . '/' . end($parameters), file_get_contents($url)); | |
} | |
$zip->close(); | |
header('Content-disposition: attachment; filename=' . $zip_name . '.zip'); | |
header('Content-type: application/zip'); | |
@readfile($zip_path); | |
unlink($zip_path); | |
exit; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment