Creating a zip archive with php

Hello,

The following code creates a zip archive with the complete file
But it adds reverse slash at the beginning of the files
What adds this backslash?

Ekran görüntüsü 2023-03-11 183020

$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
	$source = realpath($source);
	global $zipyorumadizinadi;
	$zip->setArchiveComment($zipyorumadizinadi);
	if (is_dir($source)) {
		$iterator = new RecursiveDirectoryIterator($source);

		$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
		$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

		foreach ($files as $file) {
			$file = realpath($file);
			if (is_dir($file)) {
				$zip->addEmptyDir(str_replace($source . '', '', $file . ''));
			} else if (is_file($file)) {
				$zip->addFromString(str_replace($source . '', '', $file), file_get_contents($file));
			}
		}
	} else if (is_file($source)) {
		$zip->addFromString(basename($source), file_get_contents($source));
	}
}
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
	$source = realpath($source);
	$sourceLength = strlen($source);
	global $zipyorumadizinadi;
	$zip->setArchiveComment($zipyorumadizinadi);
	if (is_dir($source)) {
		$iterator = new RecursiveDirectoryIterator($source);

		$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
		$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

		foreach ($files as $file) {
			$file = realpath($file);
			$relativePath = substr($file, $sourceLength);

			if (is_dir($file)) {
				$zip->addEmptyDir(ltrim($relativePath, '/\\'));
			} else if (is_file($file)) {
				$zip->addFromString(ltrim($relativePath, '/\\'), file_get_contents($file));
			}
		}
	} else if (is_file($source)) {
		$zip->addFromString(basename($source), file_get_contents($source));
	}
}

It looks like the problem is in the way you are constructing the paths inside the ZIP file. Specifically, when you are using str_replace($source . '', '', $file . '') , it’s removing $source from $file , but it’s not handling the directory separator correctly.

I have used the ltrim function is used to remove any leading slashes or backslashes from the relative paths, so they will have the correct format inside the ZIP file.
Hope this works

1 Like

Thank you very much, the problem is fixed
Annotate-a-local-image2

@Adem you are welcome,
Good day

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service