本文介绍了删除 FTP 连接上的文件夹和所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试添加使用 FTP 删除文件夹以及该文件夹中包含的所有子文件夹和文件的功能.

Trying to add the ability to delete a Folder using FTP and all subfolders and files contained within that folder.

我为此构建了一个递归函数,感觉逻辑是对的,但还是不行.

I have built a recursive function to do so, and I feel like the logic is right, but still doesnt work.

我做了一些测试,如果路径只是一个空文件夹或只是一个文件,我可以在第一次运行时删除,但如果它是包含一个文件的文件夹或包含一个空子文件夹的文件夹,则无法删除.因此,遍历文件夹并使用删除功能似乎是一个问题.

I did some testing, I am able to delete on first run if the path is just an empty folder or just a file, but can't delete if it is a folder containing one file or a folder containing one empty subfolder. So it seems to be a problem with traversing through the folder(s) and using the function to delete.

有什么想法吗?

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);
    }
};

推荐答案

好的,找到了我的问题.由于我没有移动到我试图删除的确切目录,因此每个被调用的递归文件的路径都不是绝对的:

Ok found my problem. Since I wasn't moving into the exact directory I was trying to delete, the path for each recursive file being called wasn't absolute:

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 连接上的文件夹和所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:34