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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?