PHP ZipArchive Removing First Character of Filenames
Get the solution ↓↓↓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".
Answer
Solution:
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 '/'.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.