2012-05-03 16 views
3

私はPHPで書いています。zipファイルの内容の絶対パス名を避ける

$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ファイルを開いたときに、サーバー全体のパスはzipファイル内にある/var/www/html/zip/archive.zipに格納されたzipファイルを持っていると思います:私は、次のコードを持っています。サーバーのパスがzipファイル内にないようにするには、どうすればいいですか?

このコマンドを実行しているスクリプトは、同じディレクトリにありません。 /var/www/html/zipfolder.php

+2

絶対パスではなく、zipに相対パスを渡すようにしてください。 'zip -r $ zip_file_location 'zip/folder'' – gcochard

答えて

5

ジップは、ファイルにアクセスするために与えられたパスを格納する傾向があります。 Gregのコメントは、あなたの現在のディレクトリツリーに固有の問題に対する潜在的な修正を提供します。より一般的に、あなたは可能性 - 少しぞんざい - あなたは最後のディレクトリが格納されている名前の一部になりたいけれども、この

$exec = "cd '$folder_to_zip' ; zip -r '$zip_file_location *'" 

のようなものは、多くの場合、(それは一種の礼儀だんので、誰でも解凍すると、すべてのダンプしません。このいずれかをテストする時間がありませんでした。自分のホームディレクトリまたは何でも)へのファイルは、テキスト処理ツールを別々の変数にそれを分割して、

$exec = "cd '$parent_of_folder' ; zip -r '$zip_file_location $desired_folder'" 

警告のようなものを実行していることを達成することができ愚かな間違いのために

+0

これはうまくいきました。あなたとGregにありがとう。 – Jason

1

これを確認してください両方のWindows上で正常に動作するPHP関数& 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(); 
} 
関連する問題