Reputation: 69
Before coming here, I've been looking for other topics and tested the provided answers and I'm still getting the same result.
So first of all, I have this folder structure.
uploads/
- student-records
-- John-Doe
--- files
---- Application
---- Transcripts
I have to zip the directory files
. The zip is working, just that it includes in the zipped the full path of the folder. Instead of the actual folder..
So I am getting this in my zip file laragon/mson/wp-content/uploads/student-records/John-Doe/files/...
Here is my actual code
$student = $student_first_name .'-'. $student_last_name.'_'.$student_id;
$upload_dir = wp_upload_dir();
$source = $upload_dir['basedir'] ."/student-records/" . $student . "/files/";
$zipFile = $upload_dir['path'] ."/student-records/" . $student . "/".$student.".zip";
// Initialize archive object
$zipArchive = new ZipArchive();
# Create a zip target
if( $zipArchive->open( $zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) !== TRUE ) {
exit("Unable to open file.");
}
// create recursive directory iterator
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceRelativePath, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
if (is_dir($sourceRelativePath)) {
foreach ($files as $file) {
$filePath = str_replace( '\\', '/', $file->getRealPath() );
if (is_dir($file)) {
$zipArchive->addEmptyDir(str_replace($source . '/', '', $filePath . '/'));
} else if (is_file($file)) {
$zipArchive->addFromString(str_replace($source . '/', '', $filePath), file_get_contents($filePath));
}
}
} else if (is_file($source)) {
$zipArchive->addFromString(basename($source), file_get_contents($source));
}
$zipArchive->close();
echo '<a href="'.$zipFileURL.'" target=""><span class="dashicons dashicons-download"></span> Download</a>';
}
I need some help so it doesn't include in the zip file the full path and just the folder files
along with its subfolders and files only.
Upvotes: 0
Views: 37