[英]Delete folder and all files on FTP connection
嘗試使用FTP以及該文件夾中包含的所有子文件夾和文件添加刪除文件夾的功能。
我已經構建了一個遞歸函數來做到這一點,我覺得邏輯是正確的,但仍然無法正常工作。
我做了一些測試,如果路徑只是一個空文件夾或只是一個文件,我可以在第一次運行時刪除,但如果它是包含一個文件的文件夾或包含一個空子文件夾的文件夾,則無法刪除。 因此,遍歷文件夾並使用刪除功能似乎是一個問題。
有任何想法嗎?
function ftpDelete($directory)
{
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
global $conn_id;
# here we attempt to delete the file/directory
if( !(@ftp_rmdir($conn_id,$directory) || @ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = @ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
ftpDelete($file);
#if the file list is empty, delete the DIRECTORY we passed
ftpDelete($directory);
}
else
return json_encode(true);
}
};
我花了一些時間在ftp上編寫我自己的遞歸刪除函數版本,這個應該是完全正常的(我自己測試過)。
嘗試並修改它以滿足您的需求,如果仍然無法正常工作則還有其他問題。 您是否檢查了要刪除的文件的權限?
function ftp_rdel ($handle, $path) {
if (@ftp_delete ($handle, $path) === false) {
if ($children = @ftp_nlist ($handle, $path)) {
foreach ($children as $p)
ftp_rdel ($handle, $p);
}
@ftp_rmdir ($handle, $path);
}
}
function recursiveDelete($handle, $directory)
{ echo $handle;
# here we attempt to delete the file/directory
if( !(@ftp_rmdir($handle, $directory) || @ftp_delete($handle, $directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = @ftp_nlist($handle, $directory);
// var_dump($filelist);exit;
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file) {
recursiveDelete($handle, $file);
}
recursiveDelete($handle, $directory);
}
}
好的,發現我的問題。 由於我沒有進入我試圖刪除的確切目錄,因此調用每個遞歸文件的路徑不是絕對的:
function ftpDeleteDirectory($directory)
{
global $conn_id;
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
# here we attempt to delete the file/directory
if( !(@ftp_rmdir($conn_id,$directory) || @ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = @ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
{
// return json_encode($filelist);
ftpDeleteDirectory($directory.'/'.$file);/***THIS IS WHERE I MUST RESEND ABSOLUTE PATH TO FILE***/
}
#if the file list is empty, delete the DIRECTORY we passed
ftpDeleteDirectory($directory);
}
}
return json_encode(true);
};
你必須檢查(使用ftp_chdir
)你從ftp_nlist
獲得的每個“文件”,以檢查它是否是一個目錄:
foreach($filelist as $file)
{
$inDir = @ftp_chdir($conn_id, $file);
ftpDelete($file)
if ($inDir) @ftp_cdup($conn_id);
}
這個簡單的技巧將起作用,因為如果ftp_chdir
有效,那么當前的$file
實際上是一個文件夾,你已經進入了它。 然后遞歸調用ftpDelete,讓它刪除該文件夾中的文件。 之后,您返回(ftp_cdup)繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.