PHP + FTP delete files in folder

倾然丶 夕夏残阳落幕 提交于 2019-12-09 13:15:26

问题


I just wrote a PHP Script which should connect to FTP and delete all files in a special folder.

It looks like this, but I have no clue what command I need to delete all files in the folder logs.

Any idea?

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

?>

回答1:


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

You might want to do some checking for directories, but at a basic level, that is it.




回答2:


The PHP manual on the FTP functions has the answers.

  • ftp_nlist() to list
  • ftp_delete() to delete

the user contributed notes give full examples for a "delete folder" function. (Handle with care.)




回答3:


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



回答4:


here is my FTP recursive delete directory solution:

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


来源:https://stackoverflow.com/questions/4069521/php-ftp-delete-files-in-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!