1

The code below successfully creates a zip file of a specified directory and all sub-directories. The problem I am having is that the end result removes the first character from each filename and folder-name within the root directory; this same behavior does not occur in the sub-directories.

<?php
    require('../config/config.php');

    $rootPath = $abs_path.'/includes/qrcodes/'; // SOURCE FOLDER TO ZIP
    $zipFilename = 'qr_images.zip';
    $zip = new ZipArchive();
    $zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE);

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

    foreach ($files as $name => $file)
    {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        if (!$file->isDir())
        {
            $zip->addFile($filePath, $relativePath);

        }else {

            if($relativePath !== false)
                $zip->addEmptyDir($relativePath);
        }
    }

    $zip->close(); 
?>

Currently the resulting zip file includes:

  • adios (folder)
    • radio_1.png
    • radio_2.png
  • nfosys (folder)
    • infosys_1.png
  • ehicles (folder)
    • vehicle_1.png
    • vehicle_2.png

The folders should be named "radios", "infosys", and "vehicles".

  • 3
    Because of `+ 1` in the `substr()` call. – Barmar May 22 '20 at 14:34
  • @Barmar Thank you for that, I feel dumb. This is what happens when you borrow code that you do not fully understand. I've removed the +1 and that solved the problem. Is there any reason why that would make sense where it is/was? – Robert Seal May 22 '20 at 14:37
  • 1
    The code you copied probably didn't have `/` at the end of `$root_path`, so it added 1 to skip over the `/` that was added as a separator in the full path. – Barmar May 22 '20 at 14:41

1 Answers1

0

The code appears to have been designed for a $rootpath variable without a trailing backslash. If you'd change it $rootPath = $abs_path.'/includes/qrcodes'; the +1 at the substr would be required. Otherwise the relative path would start with a '/'.

Joeri Noort
  • 66
  • 1
  • 3