2011-08-03 83 views
0

我正在使用此代碼讀取名爲(保護)的受保護目錄(用戶名&密碼)內容。在PHP中使用ZipArchive類

<?php 
require_once("admin/global.inc.php"); 

// increase script timeout value 
ini_set('max_execution_time', 300); 

//Generate a new flag 
$random = (rand(000000,999999)); 
$date = date("y-m-d"); 

// create object 
$zip = new ZipArchive(); 

// open archive 
if ($zip->open("$date-$random.zip", ZIPARCHIVE::CREATE) !== TRUE) { 
    die ("Could not open archive"); 
} 

// initialize an iterator 
// pass it the directory to be processed 
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("protect/")); //check question #2 

// iterate over the directory 
// add each file found to the archive 
foreach ($iterator as $key=>$value) { 
     if ($key != 'protect/.htaccess') 
       { 
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");   
$query="INSERT INTO `archives_logs` (`id`, `file`, `flag`, `date`) VALUES (NULL, '$key', '$random', '$date')"; 
      $query_result = mysql_query ($query); 
       } 
} 

// close and save archive 
$zip->close(); 
echo "Archive created successfully.";  
?> 

如果我把我的代碼文件中除受保護的目錄位置differerent的位置,我必須要改變被壓縮這是很好的目錄的路徑,但問題是,在路徑中的所有目錄都包括在Zip檔案中。 因此,如果打開壓縮文件獲得:網絡/用戶名/的public_html /等等

這裏是目錄晶格結構: WWW /保護/(文件被壓縮在這裏) WWW/compress_code.php(這裏是我當前的代碼文件)

,我希望把我的代碼文件的路徑爲: WWW /保護/管理/文件/ compress_code.php

Q1)我如何保持我的代碼文件中的最後提到的位置,而不包括我的ZipArchive文件中的路徑? Q2)當我的代碼位於要壓縮目錄的相同位置,並且當我打開我看到的壓縮文件時,保護/(文件)。我是否可以僅添加Zip檔案中保護目錄的內容而不包含目錄本身?

回答

0

這很簡單:

  1. 存儲在一個變量的目標路徑。
  2. 在添加文件之前,從本地名稱中刪除目標路徑。

像這樣:

$flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::SKIP_DOTS; 
$target = 'protect/'; 
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target, $flags)); 

foreach ($iterator as $key=>$value) { 
    if ($key != "{$target}.htaccess") 
    { 
     $localname = substr($key, strlen($target)); 
     $zip->addFile($key, $localname) or die ("ERROR: Could not add file: $key"); 
    } 
} 

這實際上應該回答兩個提問。