删除FTP连接中的文件夹和所有文件
问题描述:
尝试添加使用FTP和该文件夹中包含的所有子文件夹和文件删除文件夹的功能。删除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);
}
};
答
好的发现我的问题。由于我没有移动到精确的目录,我试图删除,每个递归文件的路径被称为是不是绝对的:
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)继续。
答
我花了一些时间用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);
}
}
不目录或任何的那就是你的子目录试图删除包含空格? – 2011-12-15 00:49:43
文件或文件夹不能有空格。只是字母字符。 – JimmyJammed 2011-12-15 00:59:22
对相关目录的文件系统权限是否允许删除目录? – sarnold 2011-12-15 01:49:43