Only folder name of a zip file?

Hello,

Folder ZIP compression. OK, no problem
Unzip extraction. OK, no problem
“2018-11-04-16-25-09_adem.zip”

I just want to get the main (original) directory name “adem”

Thank

Adem, the FILE you posted is not a FOLDER or DIRECTORY name. It is just a filename.
Do you mean that you want to pull out the data between the underscore and extension in the filename?

You can pull out just the filename without the extension this way:
$filename = “xyz123_adem.zip”;
$path_parts = pathinfo($filename);
echo $path_parts[‘filename’];
This would give you “xyz123_adem” only.

If your filename is always in the same format you can use preg_match() function or even the explode() function to separate everything by the underscore. You could even use str_pos() to locate the underscore and substr() to pull out the needed part. Here is just one way:
$filename = “xyz123_adem.zip”;
$path_parts = pathinfo($filename);
$new_filename = explode( “_”, $path_parts[‘filename’] );
echo $new_filename[1];

This takes your incoming filename, gets it without the extension. Then, explodes it at the underscore.
That creates an array of the left and right sides of the filename and you just use the second item.
Should work…

Thank you for the answer,

For me, this is not the solution.

$this->zip = new ZipArchive;
Get this class with the original directory name

Whatever the file name. Extract result folder name: “adem”
Video 1,5MB https://files.fm/u/qfh85we4

Well, the pathinfo() function will get the full path of the file.
If the file is in zipped_files\user_name\adem\zip999\ 2018-11-04-16-25-09_adem.zip then it will get the entire path. You can then parse thru the folders to get the one you need.

In PHP on the server, every file has a full path. The path is normally, the path where the code is being run from and other folders inside that path. You just need to create code to pull out the previous folder name.

Another example. If you have all of your PHP code stored in a folder on your server named “root/tests/” and the file name of the page you are viewing is called “get_zip_list.php”, then the full path would be:
“root/tests/get_zip_list.php”
And, the pathinfo() function would show that. You would just need to “explode” the path with “/” to get the parts of it and use the correct one.

Not sure this helps explain it. I am assuming you are not talking about RIGHT-CLICK “context” menus on your computer end? That has nothing to do with PHP and is linked to CLIENT-SIDE app’s not SERVER-SIDE PHP programs.

Does any of this help? Perhaps more info on what you are trying to do is needed for us?

So, programmatically unzip the contents loaded?

Is this the correct coding?

$za = new ZipArchive();

$za->open(’./2018-11-06-23-44-30_webtrees-adem.zip’);

$arr = $za->statIndex(1);
$name = $arr[“name”]; // …//webtrees-/addmedia.php
$namee = dirname($name); // …//webtrees-
$new_filename = explode("…//", $namee);
echo $new_filename[1]; // webtrees-

Result: webtrees-
Real directory name: webtrees-

@ErnieAlex, I don’t know English, I am using google translation
But I understood the subject, root/tests/

This root/tests/ issues important

Is this more accurate code?

$za = new ZipArchive();

$za->open(’./2018-11-06-23-44-30_webtrees-adem.zip’);

$arr = $za->statIndex(1);
$name = $arr[“name”]; // …//webtrees-/addmedia.php
$namee = dirname($name); // …//webtrees-
$new_filename = explode("/", $namee);
echo end($new_filename); // webtrees-

Hopefully we can help. Your language does not matter as long as we can understand the translation.

The last code shows how to get the folder name.

For using the ZipArchive() function to create a zip, you would need to insert files into the .zip file.
To insert a file into your zip, you do it this way:

$zip = new ZipArchive;
$zip->open('new-zip-filename-goes-here') ;
$zip->addFile('path-to-file-to-be-added/file-to-be-added.txt');
$zip->close();

You create a new zip object as you did.
You open a filename for the zip.
You add one or more file(s) to the zip.
You close the zip.

If you need to add more than one file to the zip, you loop thru them by using the addFile() over as needed.

For using the ZipArchive() function to open zip files, you need to know where you want to store them.
I think this is what you are trying to do. If so, you would get the folder name as you did in your last code.
Then, extract the zipped file in this way:

$za = new ZipArchive();
$za->open(’./2018-11-06-23-44-30_webtrees-adem.zip’);
$arr = $za->statIndex(1);
$name = $arr[“name”];
$namee = dirname($name);
$new_filename = explode("/", $namee);
$folder_name = end($new_filename);
$za->extractTo($folder_name);
$za->close();

This would get the folder name from your zip file name.
Then, it would extract the files in the zip into the folder.

Hope this helps.

I’m beginner

The compression code I use
Where should I add this? ```
$zip->open(‘new-zip-filename-goes-here’) ;
I like this code, doing very fast compression

Compress form cpanel: https://i.hizliresim.com/LDJVjz.png
Compress with my script: https://i.hizliresim.com/r1qlGz.png

[php]
$starttime = microtime(true);

date_default_timezone_set('Europe/Istanbul');
$simdizaman = date("Y-m-d-H-i-s",time());
 
// Create ZIP file
if(isset($_POST['name'])){

 $zip = new ZipArchive();
 $filename = ZIPDIR.$simdizaman."_".$_POST['name'].".zip";

 if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
  exit("cannot open <$filename>\n");
 }

 $dir = DIZINDIR.$_POST['name']."/";

 // Create zip
 createZip($zip,$dir);

 $zip->close();
}

// Create zip
function createZip($zip,$dir){
 if (is_dir($dir)){

  if ($dh = opendir($dir)){
   while (($file = readdir($dh)) !== false){
 
    // If file
    if (is_file($dir.$file)) {
     if($file != '' && $file != '.' && $file != '..'){
 
      $zip->addFile($dir.$file);
     }
    }else{
     // If directory
     if(is_dir($dir.$file) ){

      if($file != '' && $file != '.' && $file != '..'){

       // Add empty directory
       $zip->addEmptyDir($dir.$file);

       $folder = $dir.$file.'/';
 
       // Read data of the folder
       createZip($zip,$folder);
      }
     }
 
    }
 
   }
   closedir($dh);
  }
 }
}

/*
// Download Created Zip file
if(isset($_POST['download'])){
 
 $filename = DIZINDIR."/".$simdizaman."_".$_POST['name'].".zip";

 if (file_exists($filename)) {
  header('Content-Type: application/zip');
  header('Content-Disposition: attachment; filename="'.basename($filename).'"');
  header('Content-Length: ' . filesize($filename));

  flush();
  readfile($filename);
  // delete file
  unlink($filename);                                                        
 
 }
}
*/
$endtime = microtime(true);
function formatPeriod($starttime, $endtime)
{
$duration = $endtime - $starttime;
$hours = floor($duration / 60 / 60);
$minutes = floor(($duration / 60) - ($hours * 60));
$seconds = floor($duration - ($hours * 60 * 60) - ($minutes * 60));
$milliseconds = ($duration - floor($duration)) * 1000;
return sprintf('%02d:%02d:%02d:%05.0f', $hours,$minutes,$seconds,$milliseconds);
}

echo "<b>".strtoupper($_POST['name'])."</b> Klasörü Başarıyla ZIP Formatına Sıkıştırıldı<br />";
echo '<br />Sıkıştırma Süresi: '.formatPeriod($starttime, $endtime).'';
[/php]

I think your problem is the use of a function to handle the zipping up of files.

Variables used inside of functions are erased once the function is completed. All variables outside of a function are called “global” variables. They can be used anywhere in your code, but, NOT inside functions. Inside the function all variables are “local” variables and only work inside the function itself.

To fix this, you need to tell the function that the variables are “global” and that will let you use them in all parts of the code. This means that you have to add one command. Like this:

// Create zip
function createZip($zip,$dir){
 global $zip, $dir;
 if (is_dir($dir)){

Adding that line lets the function use these two items just like any other variable.
Your current code adds values to the $zip variable, which is really an object. But, these are not allowed
outside the function since the function thinks it is a “local” only variable.

Try this and let us know if it solves it for you.

https://i.hizliresim.com/dvzoo4.png

Line 31:
// Create zip
createZip($zip,$dir);

Line 62:
// Read data of the folder
createZip($zip,$folder);

Line 39:
if (is_dir($dir)){

zip file created, but nothing has changed

I’ve found a new script that does exactly what I want.
However, it is very slow
Test result:
Test folder size: 1.41GB
Time zipped with the above code: 1 minute 17 seconds.
Time zipped with the following code: 4 minute 20 seconds

Code source

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

$rootPath = realpath(’./mainfolder/test1/test2/test3/adem’);
I have added
$foldernumber = strlen(‘adem’);
$relativePath = substr($filePath, strlen($rootPath) - $foldernumber);

Result:

Is it possible to speed up this code?
OR
First code to remove the slash and folder path

This process seems slow when I tested it last year for another project.
It bogged down when there was a lot of files.

I can not see your PNG images as they just display a 403 Error.

Doing some research for you, I found a slightly different version of this same code. It might work better for you. Try it and let us know:

<?php
$starttime = microtime(true);

date_default_timezone_set('Europe/Istanbul');
$simdizaman = date("Y-m-d-H-i-s",time());
 
// Create ZIP file
if(isset($_POST['name'])){

 $zip = new ZipArchive();
 $filename = ZIPDIR.$simdizaman."_".$_POST['name'].".zip";

 if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
  exit("cannot open <$filename>\n");
 }

 $dir = DIZINDIR.$_POST['name']."/";

//  Initialize an iterator, passing it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

// Iterate over the directory, add each file found to the archive
foreach ($iterator as $key=>$value) {
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}

//  Close and save archive
$zip->close();
?>

Not completely sure if this solves it, but try it and let us know.

Thank you very much for your attention

The following error
Warning: ZipArchive::close(): Read error: Bad file descriptor in

You do not close this IF clause. You are missing a brace " } "

I ran some tests and found this version to work.
(I did not adjust it to match your version. You will have to put in your file name for the output and folder name for the folder to zip up. I used the current folder to zip up for testing.)
This worked quite fast on my live server and created the full site’s zip file fast enough for me… Try it!
<?PHP
echo "Started: " . date(“Y-m-d-H-i-s”,time()) . “

”;

// Get real path for our folder
$rootPath = realpath('./');  //  Change this to your folder to zip

// Initialize archive object
$zip = new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);  //  Change test.zip to your filename

// Create recursive directory iterator
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file) {
    // Skip directories (they would be added automatically)
    if (!$file->isDir()) {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

echo "Ended: " . date("Y-m-d-H-i-s",time());
?>

I tested it on two different folders and it appears to zip up all of the files and does it fast enough on my server for the two test folders. Only took a few seconds. On your larger files, it might take longer. Let us know how long this version takes and show us your new code…

Test: 1.41GB, 1 minute 11 secends
I’m gonna use this,
Thank you very much

Great! Glad it works for you. Sorry it took so long to solve it. Sometimes it just takes a lot of research to locate the final solution!

Thank you very much for your help

Yes, for the better.

I use this way
I wrote the folder name in the comment(Good idea)
if($_POST[‘zipyap’] == 1 AND isset($_POST[‘klasoradi’])){

$starttime = microtime(true);
$simdizaman = date(“Y-m-d-H-i-s”,time());

$rootPath = realpath(DIZINDIR.$_POST[‘klasoradi’]);

// Initialize archive object
$zip = new ZipArchive();

// Dosya adı oluştur
$filename = ZIPDIR.$simdizaman."_".$_POST[‘klasoradi’].".zip";

$zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files **/

$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);

// How many characters in the directory name
$foldernumber = strlen($_POST[‘klasoradi’]);

foreach ($files as $name => $file)
{

// Skip directories (they would be added automatically)
if (!$file->isDir())
{
    // Get real and relative path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) - $foldernumber);

    // Add directory name to archive comment
    $zip->setArchiveComment($_POST['klasoradi']);
    // Add current file to archive        
    $zip->addFile($filePath, $relativePath);
    //echo "<pre>";
    //print_r($relativePath);
    //echo "<pre>";
}

}

// Zip archive will be created only after closing object
$ret = $zip->close();

$endtime = microtime(true);

function formatPeriod($starttime, $endtime) {
$duration = $endtime - $starttime;
$hours = floor($duration / 60 / 60);
$minutes = floor(($duration / 60) - ($hours * 60));
$seconds = floor($duration - ($hours * 60 * 60) - ($minutes * 60));
$milliseconds = ($duration - floor($duration)) * 1000;
return sprintf(’%02d:%02d:%02d:%05.0f’, $hours,$minutes,$seconds,$milliseconds);
}

if (file_exists($filename) AND $ret) {
echo “”.strtoupper($_POST[‘klasoradi’])." Klasörü Başarıyla ZIP Formatına Sıkıştırıldı
";
echo ‘
Sıkıştırma Süresi: ‘.formatPeriod($starttime, $endtime).’’;
} else {
echo “BİR HATADAN DOLAYI ZIP DOSYASI OLUŞTURULAMADI”;
}

} // if($_POST[‘zipyap’] == 1 AND isset($_POST[‘klasoradi’])){

This line was in the code I found. It is not needed. I edited it out but you must have read it before I did.
Not needed. And, the speed of it seems great for you too. See you in your next question… LOL

Sponsor our Newsletter | Privacy Policy | Terms of Service