Drupal Technical
[Drupal 6] How to unzip a zipped file from within Drupal?
In one of our Drupal projects we were requested to create a Drupal module through which you could upload and extract a zip file and store the extracted files into the files directory in the Drupal site. If you are faced with the same task and wanted to know how to unzip a zipped file from within Drupal.
Simply follow the steps below for extracting and storing the zip files from within Drupal.
- Upload the zipped file using a Drupal CCK field attached to the content type.
- Implement a callback function while inserting or updating the node form.
- Extract the zipped file into a temp folder
- All the extracted files in temp folder should be copied to a 'flash' folder in sites/default/files path.
- Finally remove the temp folder.
Have a look at the above steps implemented in the code below.
function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($node->type ==[content_type]) {
if ($op == "update" || $op == "insert") {
$return = hook_unzip_file($node->field_upload_theme_file[0]['filepath'], 'flash');
}
}
// The extracted file save to 'sites/default/files/flash' folder.
function hook_unzip_file($file_path, $op) {
$zip = new ZipArchive();
$res = $zip->open($file_path);
if ($res === TRUE) {
if (!is_dir(file_directory_path() . "/temp_". $op)) {
mkdir(file_directory_path() . "/temp_". $op, 0777);
}
$zip->extractTo(file_directory_path() . "/temp_". $op . "/");
$zip->close();
$dh = opendir(file_directory_path() . "/temp_". $op);
while (FALSE !== ($obj = readdir($dh))) {
if ($obj=='.' || $obj=='..'||$obj=='__MACOSX') continue;
if (is_dir(file_directory_path() . "/temp_". $op . "/" . $obj)) {
if (!is_dir(file_directory_path() . "/" . $op)) {
mkdir(file_directory_path() . "/" . $op, 0777);
}
// copy the files from temp file to original folder
// remove the temp directory
}
}
return TRUE;
}
}
Hope that was helpful in your Drupal module development. If you have any doubts regarding this article or simply use the comments box below.
References: