2012-05-03 100 views
3

我正在用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

+2

您應該嘗試將相對路徑傳入'zip'而不是完整路徑。 'zip -r $ zip_file_location'zip/folder'' – gcochard

回答

5

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

1

請檢查這個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(); 
}