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

5

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

它看起来像是这样的,但我不知道需要哪个命令才能删除logs文件夹中的所有文件。

有什么想法吗?

<?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个回答

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

你可能想要检查一些目录,但基本上就是这样。


@Lukas:该死,我甚至之前还双重检查了foreach的语法。xD 感谢你发现了这个错误。/已编辑 - Reese Moore
有没有办法指定要删除的特定文件扩展名,例如*.jpg? - Dan Cundy

4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接