簡體   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