尝试使用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);
}
};
答案 0 :(得分:4)
我花了一些时间在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);
}
}
答案 1 :(得分:1)
好的发现了我的问题。由于我没有进入我试图删除的确切目录,因此调用每个递归文件的路径不是绝对的:
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);
};
答案 2 :(得分:1)
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);
}
}
答案 3 :(得分:0)
您必须检查(使用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)继续。