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

时间:2010-11-01 13:58:33

标签: php ftp delete-file

我刚写了一个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);

?>

4 个答案:

答案 0 :(得分:14)

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

您可能希望对目录进行一些检查,但在基本级别,就是它。

答案 1 :(得分:4)

PHP manual on the FTP functions有答案。

用户提供的注释为{delete}文件夹提供full examples功能。 (小心轻放。)

答案 2 :(得分:1)

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

答案 3 :(得分:0)

这是我的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);
}