Last active
December 16, 2015 17:29
-
-
Save tomasvitek/5470631 to your computer and use it in GitHub Desktop.
Simple utility which creates a zip archive with contents of the folder it is placed in. This script comes in handy when you don't have SSH access to your (shared) webserver. Upload the script to the webserver, open url `http://example.com/compress.php`. Script creates archive `http://example.com/__name-of-folder.zip`.
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
<?php | |
/** | |
* Compress a folder to a zip archive | |
* | |
* Simple utility which creates a zip archive with contents of the folder it is placed in. | |
* This script comes in handy when you don't have SSH access to your (shared) webserver. | |
* Upload the script to the webserver, open url `http://example.com/compress.php`. | |
* Script creates archive `http://example.com/__name-of-folder.zip`. | |
* | |
* @copyright Copyright (c) 2013 Tomas Vitek | |
* @author Tomas Vitek ~ http://tomasvitek.com | |
* @link Compress function inspired by http://stackoverflow.com/a/1334949 | |
* @version 0.1 | |
*/ | |
function compress($source, $destination) | |
{ | |
if (!file_exists($source)) { | |
return false; | |
} | |
$zip = new ZipArchive(); | |
if (!$zip->open(__DIR__ . '/' . $destination, ZIPARCHIVE::CREATE)) { | |
return false; | |
} | |
$source = str_replace('\\', '/', realpath($source)); | |
if (is_dir($source) === true) { | |
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); | |
foreach ($files as $file) { | |
$file = str_replace('\\', '/', $file); | |
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..', $destination)) ) | |
continue; | |
$file = realpath($file); | |
if (is_dir($file) === true) { | |
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); | |
} | |
else if (is_file($file) === true) { | |
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); | |
} | |
} | |
} | |
else if (is_file($source) === true) { | |
$zip->addFromString(basename($source), file_get_contents($source)); | |
} | |
return $zip->close(); | |
} | |
if (compress(__DIR__, '__' . basename(__DIR__) .'.zip') === TRUE) { | |
echo '<h1>Done! 👍</h1>'; | |
} else { | |
echo '<h1>Failed! 👎</h1><p>Check if the folder exists or if PHP can write to the folder.</p>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment