繁体   English   中英

PHP + FTP 删除文件夹中的文件

[英]PHP + FTP delete files in folder

我刚刚写了一个 PHP 脚本,它应该连接到 FTP 并删除一个特殊文件夹中的所有文件。

看起来像这样,但我不知道删除文件夹日志中的所有文件需要什么命令。

有什么想法吗?

<?php

// set up the settings
$ftp_server = 'something.net';
$ftpuser = 'username';
$ftppass = 'pass';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftpuser, $ftppass);

// delete all files in the folder logs
????????

// close the connection
ftp_close($conn_id);

?>
// Delete all files in the folder logs
$logs_dir = "";
ftp_chdir($conn_id, $logs_dir);
$files = ftp_nlist($conn_id, ".");
foreach ($files as $file)
{
    ftp_delete($conn_id, $file);
}    

您可能想要对目录进行一些检查,但在基本级别上,就是这样。

关于 FTP 函数PHP 手册有答案。

用户贡献的注释给出了“删除文件夹”功能的完整示例 (小心处理。)

<?php

# server credentials
$host = "ftp server";
$user = "username";
$pass = "password";

# connect to ftp server
$handle = @ftp_connect($host) or die("Could not connect to {$host}");

# login using credentials
@ftp_login($handle, $user, $pass) or die("Could not login to {$host}");

function recursiveDelete($directory)
{
# 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);

# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
{
recursiveDelete($file);
}

#if the file list is empty, delete the DIRECTORY we passed
recursiveDelete($directory);
}
}
?>

这是我的 FTP 递归删除目录解决方案:

/**
 * @param string $directory
 * @param resource $connection
 */
function deleteDirectoryRecursive(string $directory, $connection)
{
    if (@ftp_delete($connection, $directory)) {
        // delete file
        return;
    }
    # here we attempt to delete the file/directory
    if( !@ftp_rmdir($connection, $directory) )
    {
        if ($files = @ftp_nlist ($connection, $directory)) {
            foreach ($files as $file) {
                // delete file or directory
                deleteDirectoryRecursive( $file, connection);
            }
        }
    }
    @ftp_rmdir($connection, $directory);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM