用PHP语言重命名所有文件和文件夹FTP



我要重命名所有文件和文件夹,我编写了一个可行和重命名文件的函数,但是当我在路径中制作文件和文件夹时,我的问题不是作为父孩子因此,当我首先重命名父级文件夹时,在函数想要重命名的孩子时,在下一个循环中说"没有这样的文件或目录",其真实错误是由于父母文件夹在几分钟前重命名

我更改了代码,但对我没有帮助FTP读取文件和文件夹的代码:

 if (!self::ftp_is_dir($resource, $thisPath)) {
        // for Files (anything that isnt a readable directory)
        if ($first == TRUE) {
            return array("Path doesn't Exist (" . $thisPath . ")");
        }
        $theList[] = $thisPath;
        return $theList;
    } else {
        $contents = ftp_nlist($resource, $thisPath);
        // For empty folders
        if (count($contents) == 0) {
            $theList[] = $thisPath;
            return $theList;
        } else {
            $theList[] = $thisPath;
        }
        // Recursive Part
        foreach ($contents As $file) {
            $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
        }
        return $theList;
    }

和这样的返回阵列在此处输入图像描述

和我用于重命名文件夹和文件的代码

$replacers = array(" ", "", "  ", "-=", "=-", '©',"!", ";", "#", "@", "'", '<', '>');
    foreach ($paths as $path) {
        if (preg_match('/' . implode('|', $replacers) . '/', $path) != 0) {
            $route = preg_replace('/ftp/', "ftp://ftp.mylocal.co", $path, 1);;
            if (is_dir($route)) {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);
                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }
            } else {
                $newName = str_replace($replacers, "_", basename($path));
                $directory = pathinfo($path);
                if (ftp_rename($connectionID, $path, $directory['dirname'] . '/' . $newName)) {
                    Logger::setLog('renaming', "Renaming: $path to $newName");
                } else {
                    Logger::setLog('failed to renaming', "Renaming: $path to $newName");
                }
            }
        }
    }

[1]:https://i.stack.imgur.com/xk3kx.png

public static function ftp_is_dir($conn, $dir)
{
    $cdir = ftp_pwd($conn);
    if (@ftp_chdir($conn, $dir)) {
        ftp_chdir($conn, $cdir);
        return true;
    } else {
        return false;
    }
}

如果有:

+ folder
  - file1
  - file2
+ folder with space
  - file with space

...您目前首先将/folder with space重命名为/folder_with_space

然后您尝试将/folder with space/file with space重命名为/folder with space/file_with_space。但是该文件不再存在。

最简单的解决方案是真正首先重命名孩子,然后是父母:

    $contents = ftp_nlist($resource, $thisPath);
    // Recursive Part
    foreach ($contents As $file) {
        $theList = self::ftp_nlistr($resource, $file, $theList, FALSE);
    }
    $theList[] = $thisPath;
    return $theList;

最新更新