避免压缩文件内容的绝对路径名称
问题描述:
我正在用php编写。我有以下代码:避免压缩文件内容的绝对路径名称
$folder_to_zip = "/var/www/html/zip/folder";
$zip_file_location = "/var/www/html/zip/archive.zip";
$exec = "zip -r $zip_file_location '$folder_to_zip'";
exec($exec);
我想有储存在/var/www/html/zip/archive.zip
zip文件,它不会,但是当我打开ZIP文件的完整服务器路径是ZIP文件。我如何编写这个以便服务器路径不在zip文件中?
运行此命令的脚本不在同一个目录中。它位于/var/www/html/zipfolder.php
答
zip会倾向于存储文件,并使用任何路径访问它们。格雷格的评论为您提供了针对当前目录树的特定修补程序。更一般地,你可以 - 有点粗暴 - 做这样的事情
$exec = "cd '$folder_to_zip' ; zip -r '$zip_file_location *'"
但往往你最想要的目录是存储的名称的一部分(这有点礼貌,让谁解压不转储全部文件到自己的主目录或其他),你可以完成,通过拆分出来与文本处理工具的独立变量,然后做一些像
$exec = "cd '$parent_of_folder' ; zip -r '$zip_file_location $desired_folder'"
警告:没有时间去测试任何这为愚蠢的错误
+0
这工作。谢谢你和格雷格。 – Jason
答
请检查这个PHP功能在Windows服务器上都可以正常工作。
function Zip($source, $destination, $include_dir = false)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = realpath($source);
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode(DIRECTORY_SEPARATOR, $source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= DIRECTORY_SEPARATOR . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
// Ignore "." and ".." folders
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..')))
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . DIRECTORY_SEPARATOR, '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
您应该尝试将相对路径传入'zip'而不是完整路径。 'zip -r $ zip_file_location'zip/folder'' – gcochard