2011-12-04 62 views
0

我想獲得一個PHP腳本來列出一個備份目錄的內容使用'拒絕所有'命令在一個。 htaccess文件。PHP腳本訪問一個目錄,否則'拒絕所有'(通過.htaccess)

這是作爲wordpress備份插件背後的推理僅適用於管理員,我想給予排名較低的用戶從在線(通過簡單的儀表板小部件)下載備份的能力。

您可以在下面找到我使用的代碼,並在遇到由於htaccess文件導致的403錯誤時跳閘。

//define the directory (this is where the backup plugin store the .zip files) 
$directory = site_url() . "/wp-content/backups/"; 

//display the generated directory for testing 
echo '<b>Scanning: </b>' . $directory . '</br></br>'; 

//display a link to a test.zip I know exists for testing 
echo '<b>Manual Link: </b> <a href="' . $directory . 'test.zip" target="_blank">test.zip</a></br></br>'; 

//get all files in the directory with a .zip extension. 
$files = glob($directory . "*.zip"); 

//print each file name as a download link 
foreach($files as $file){ 
    echo '<a href="' . $file . '">' . $file . '</a> </br>'; 
} 

你可以提供的任何幫助將是最有幫助的。

謝謝, Andy。在代碼

更新,使水珠正常工作

//Define the backup folder location 
$backup_location = "wp-content/backups/"; 

//Set the file directory for glob 
$directory = $_SERVER['DOCUMENT_ROOT'] . $backup_location; 

//Prints the directory for testing purposes 
echo '<b>Scanning: </b>' . $directory . '</br></br>'; 

//Filter the discovered files 
$files = glob($directory . "*.*"); 

//Echo the filtered files 
foreach($files as $file){ 
    echo '<a href="' . site_url() . '/' . $backup_location . basename($file) . '">' . basename($file) . '</a> </br>'; 
} 
+0

site_url()返回什麼? –

+0

這是一個WordPress變量,返回站點URL(在WP後端定義)。雖然從其他評論看來,glob不能通過url的工作。 –

+0

是的,這是真的,glob不通過HTTP工作。改用本地路徑。 htaccess不限制通過文件系統訪問,所以你不應該有任何問題。 –

回答

1

您目前只是提供了鏈接文件的用戶沒有訪問。沒有添加任何權利,這將不起作用。

這個設置的工作原理是使用當前頁面實際向用戶提供文件。

你基本上做的是讓php讀取文件(它有權訪問該文件),向用戶發送標題,然後發送內容。使用類似的代碼從PHP手冊中的例子:

http://php.net/manual/en/function.readfile.php

<?php 
$file = 'monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    exit; 
} 
?> 
+0

謝謝。當我根據glob返回生成文件名時,可能會有多個文件。我將如何使用此腳本顯示下載鏈接? –

+0

我會使用第一個腳本來創建鏈接,但通過上面的腳本和get參數('/site/downloadfile.php?file = yourfilename')將它們鏈接到一個文件。進行一些檢查以確保只有你想要的文件可以被提供,但最後使用'$ file = $ _GET ['file']'來獲取文件名。 – Nanne

1

你的問題是這樣的:

$directory = site_url() . "/wp-content/backups/"; 

你無法通過HTTP做目錄列表。這不起作用(不管訪問限制)。您需要在本地目錄上運行​​3210等。

$directory = "./wp-content/backups/"; 

它說正確的,因此glob手冊頁:

注:此功能不會作用於遠程文件,被檢查的必須通過服務器的文件系統訪問。

+0

謝謝。我改變了我的代碼來反映這種行爲。它沒有解決訪問問題,但是它阻止了我錯誤地聲稱代碼會起作用;)(請參閱關於代碼的郵件Q更新) –

+0

不,請理解您的意思。但直接下載鏈接顯然會失敗,除非你像#Nanne解釋的那樣實現訪問包裝。 – mario

相關問題