Remove Old Remote FTP Folders

2019-07-15 18:54发布

I've written a MySQL database backup script which store backup files in remote FTP server. It creates some folders in root named by database name, then in each of them it creates some folders named by current date (Format: yyyy-mm-dd), and it these folders it uploads the backup files named by exact time.

I also need to remove old second level folders (which are named by date); I mean the folders older than 4 days. This is the part I've problem with. I tried some codes with ftp_nlist and I could list folders with it, I also ftp_mdtm to get the creation date and compare it with expiration date. But the result was not okay. Here is my code:

...

$skip = array('.', '..', '.ftpquota', '.htaccess');
$expire_date = date('Y-m-d', strtotime('-4 days', time()));

$ff_list = ftp_nlist($con, $db_dir);
foreach($ff_list as $item)
{
    if(in_array($item, $skip))
    {
        continue;
    }
    $mod_time = ftp_mdtm($con, $item);
    if(strtotime($expire_date ) >= $mod_time)
    {
        ftp_rmdir($con, $item);
    }
}

...

Please attend I need to remove the old folders with all of their contents, So I need the suitable remove command (I don't know if ftp_rmdir works properly).

标签: php ftp
2条回答
时光不老,我们不散
2楼-- · 2019-07-15 19:33

your using the correct command ftp_rmdir

http://php.net/manual/en/function.ftp-rmdir.php

but i bet the problem is that this function, like rmdir, requires the directory be empty.

here's a recursive delete function WARNING! UNTESTED!

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

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

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

function recursiveDelete($directory){
    //try to delete
    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 each file in the list
        foreach($filelist as $file){
            recursiveDelete($file);
        }

        //if the file list is empty, delete the directory we passed
        recursiveDelete($directory);
    }
}
查看更多
放荡不羁爱自由
3楼-- · 2019-07-15 19:35

Try this :

if(strtotime($expire_date ) >= strtotime($mod_time))
查看更多
登录 后发表回答