0

I would like to delete in a FTP folder (and subfolders) all files that contain "2019" string in the name

For example 201902_QSA4_CA.pdf => This file will be deleted

Here my code, but not run:

$web = 'mipage.com';
$user = 'xxxx';
$pass = 'xxxx';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);

$it = new RecursiveDirectoryIterator("pdfs/archivo/");
$display = Array ('2019');
foreach(new RecursiveIteratorIterator($it) as $file)
{
    if (in_array(reset(explode('.', $file)), $display))
        unlink($file);
}
ftp_close($conn_id);

Someone can help me?

Thxs

Regards

1
  • You are not actually reading anything via the FTP connection to begin with. Commented Nov 2, 2021 at 12:18

1 Answer 1

1

ftp_nlist will allow you to use a wildcard to get file list.

$web = 'mipage.com';
$user = 'xxxx';
$pass = 'xxxx';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);
ftp_pasv($conn_id, true);

$files = ftp_nlist($conn_id, "/pdfs/archivo/2019*");

foreach ($files as $file_name)
{
    ftp_delete($conn_id, $file_name);
}

If you need to find subdirectories recursively, you can do it like this.

$web = 'mipage.com';
$user = 'xxxx';
$pass = 'xxxx';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);
ftp_pasv($conn_id, true);

$files = [];
$ftpRecursiveSearcher = function ($path, $pattern) use (&$ftpRecursiveSearcher, &$files, &$conn_id)
        {
            $list = ftp_nlist($conn_id, $path);
            foreach ($list as $name)
            {
                if (ftp_size($conn_id, $name) === -1)
                {
                    $ftpRecursiveSearcher($name, $pattern);
                    $targets = ftp_nlist($conn_id, "{$name}/{$pattern}");
                    $files = array_merge($files, $targets);
                }
            }
        };

$ftpRecursiveSearcher('pdfs/archivo', '2019*'); // 'pdfs/archivo' is relative path

array_walk($files, function ($file) use (&$conn_id) {
            ftp_delete($conn_id, $file); 
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.