Skip to content

Commit 43c0e99

Browse files
committed
zip
1 parent b73c2ca commit 43c0e99

File tree

1 file changed

+65
-1
lines changed

1 file changed

+65
-1
lines changed

src/Util.php

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ public static function set_values($defaults, $values, $default_key = "") {
390390
* @return array [description]
391391
*/
392392
public static function read_csv($filename, $with_header = true, $headers = null, $delimiter = ',') {
393-
$data = array();
393+
$data = [];
394394
$index = 0;
395395
$header_count = $headers ? count($headers) : 0;
396396

@@ -864,6 +864,70 @@ public static function to_object($array, $recursive = false) {
864864
], $array);
865865
else return $array;
866866
}
867+
868+
public static function unzip($zip_file, $extract_path = null) {
869+
$zip = new \ZipArchive;
870+
if ($zip->open($zip_file)) {
871+
if (!$extract_path) {
872+
$path_info = pathinfo($zip_file);
873+
$extract_path = $path_info['dirname'].DS;
874+
}
875+
876+
$zip->extractTo($extract_path);
877+
$zip->close();
878+
return true;
879+
880+
} return false;
881+
}
882+
883+
/**
884+
* Create a compressed zip file
885+
* @param array $files files (filename => file_location)
886+
* @param string $destination destination of the zip file
887+
* @param boolean $overwrite overwrite if zip file exists
888+
* @return [type] true if success, otherwise false
889+
*/
890+
public static function zip($files = [], $destination = '', $overwrite = false) {
891+
// if the zip file already exists and overwrite is false, return false
892+
if (file_exists($destination) && !$overwrite) {
893+
return false;
894+
}
895+
896+
$valid_files = [];
897+
$files = is_array($files) ? $files : [$files];
898+
// if files were passed in...
899+
if ($files) {
900+
// cycle through each file
901+
foreach ($files as $filename => $file) {
902+
// make sure the file exists
903+
if (file_exists($file)) {
904+
if (is_int($filename)) $filename = basename($file);
905+
$valid_files[$filename] = $file;
906+
}
907+
}
908+
}
909+
910+
// if we have good files...
911+
if (count($valid_files)) {
912+
// create the archive
913+
$zip = new \ZipArchive();
914+
if ($zip->open($destination, \ZipArchive::OVERWRITE | \ZipArchive::CREATE) !== true) {
915+
return false;
916+
}
917+
// add the files
918+
foreach ($valid_files as $filename => $file) {
919+
$zip->addFile($file, $filename);
920+
}
921+
922+
// close the zip -- done!
923+
$zip->close();
924+
925+
// check to make sure the file exists
926+
return file_exists($destination);
927+
} else {
928+
return false;
929+
}
930+
}
867931
}
868932

869933
?>

0 commit comments

Comments
 (0)