duanke1984 2008-11-09 15:45
浏览 60
已采纳

使用PHP删除FTP存档中具有特定名称的所有目录

How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?

To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.

  • 写回答

3条回答 默认 最新

  • 普通网友 2008-11-09 20:13
    关注

    Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly.

    function scan_ftp_dir($conn, $dir, $pattern) {
        $files = ftp_nlist($conn, $dir);
        if (!$files) {
            return;
        }
    
        foreach ($files as $file) {
            //the quickest way i can think of to check if is a directory
            if (ftp_size($conn, $file) == -1) {
    
                //get just the directory name
                $dirName = substr($file, strrpos($file, '/') + 1);
    
                if (preg_match($pattern, $dirName)) {
                    echo $file . ' matched pattern';
                } else {        
                    //directory didn't match pattern, recurse   
                    scan_ftp_dir($conn, $file, $pattern);
                }
            } 
        }
    }
    

    Then do something like this

    $host = 'localhost';
    $user = 'user';
    $pass = 'pass';
    
    
    if (false === ($conn = ftp_connect($host))) {
        die ('cannot connect');
    }
    
    if (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');
    
    
    scan_ftp_dir($conn, '.', '/^beginswith/');
    

    Unfortunately you can only delete an empty directory with ftp_rmdir(), but if you look here there is a function called ftp_rmAll() which you could use to remove whole directory structures which you find.

    Also I have only tested on Unix the trick of using the fail status returned from ftp_size() as a method of checking if an item returned by ftp_nlist() is a directory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据