我用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);
我想将 zip 文件存储在它确实存在的/var/www/html/zip/archive.zip
但是当我打开该 zip 文件时,整个服务器路径都在 zip 文件中。 我如何编写它以使服务器路径不在 zip 文件中?
运行此命令的脚本不在同一目录中。 它位于/var/www/html/zipfolder.php
zip 倾向于使用访问它们的任何路径存储文件。 Greg的评论为您提供了特定于当前目录树的潜在修复程序。 更一般地说,你可以 - 有点粗略 - 做这样的事情
$exec = "cd '$folder_to_zip' ; zip -r '$zip_file_location *'"
通常,尽管您希望最后一个目录成为存储名称的一部分(这有点礼貌,因此解压缩的人不会将所有文件转储到他们的主目录中或其他任何内容),但您可以通过使用文本处理工具将其拆分为一个单独的变量,然后执行类似
$exec = "cd '$parent_of_folder' ; zip -r '$zip_file_location $desired_folder'"
警告:没有时间测试任何愚蠢的错误
请检查这个PHP函数,它在Windows和Linux服务器上都工作正常。
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();
}