Current Location: Home> Latest Articles> Sharing of application skills and practical cases of ftp_rawlist function in command line scripts

Sharing of application skills and practical cases of ftp_rawlist function in command line scripts

gitbox 2025-05-26

In PHP development, especially when it comes to tasks that automate file management or remote server interaction, ftp_rawlist() is a very useful function. It allows developers to obtain the original list information of directories through the FTP protocol, which is very critical for fine-grained processing of files on FTP servers. This article will explore in-depth skills of using the ftp_rawlist() function, and combine practical cases to show its application in command-line scripts.

1. Function introduction

ftp_rawlist() is one of the functions provided by the PHP FTP extension, and the prototype is as follows:

 array ftp_rawlist ( FTP\Connection $ftp_stream , string $directory [, bool $recursive = false ] )

This function returns the detailed information of all files and subdirectories in the specified directory, and the format is usually the same as the ls -l command. This means that you can extract permissions, file size, modification time, file name and other information from the returned string.

2. Reasons suitable for use in command line scripts

In CLI (command line interface) scripts, the role of ftp_rawlist() is particularly obvious, and the main reasons include:

  1. Automatically process remote directory structure without GUI interaction

  2. Suitable for periodic tasks such as checking the FTP directory via Cron timed

  3. Supports custom logical parsing directory structure

3. Practical case 1: List files in a certain directory and filter out files modified within the last 7 days

 <?php

$ftp = ftp_connect('ftp.gitbox.net');
ftp_login($ftp, 'username', 'password');

$rawList = ftp_rawlist($ftp, '/public_html/files');

$recentFiles = [];
$now = time();

foreach ($rawList as $line) {
    $parts = preg_split("/\s+/", $line, 9);
    if (count($parts) < 9 || $parts[0][0] === 'd') {
        continue; // Ignore the directory
    }

    $month = $parts[5];
    $day = $parts[6];
    $timeOrYear = $parts[7];
    $filename = $parts[8];

    $filetime = strtotime("$month $day $timeOrYear");
    if ($filetime !== false && ($now - $filetime) <= 7 * 24 * 60 * 60) {
        $recentFiles[] = $filename;
    }
}

print_r($recentFiles);

ftp_close($ftp);

This script will connect to the FTP server on ftp.gitbox.net , obtain all files in the /public_html/files directory, and filter out the file names modified in the last 7 days.

4. Practical case 2: Recursively list all files and download them to the local area

Recursive support is not a built-in feature of ftp_rawlist() , but we can implement it ourselves through recursive functions:

 <?php

function listAllFiles($ftp, $dir = '.', $base = '') {
    $files = [];

    $list = ftp_rawlist($ftp, $dir);

    foreach ($list as $item) {
        $info = preg_split("/\s+/", $item, 9);
        $name = $info[8];
        $fullPath = "$dir/$name";

        if ($info[0][0] === 'd') {
            $files = array_merge($files, listAllFiles($ftp, $fullPath, "$base$name/"));
        } else {
            $files[] = "$base$name";
        }
    }

    return $files;
}

$ftp = ftp_connect('ftp.gitbox.net');
ftp_login($ftp, 'username', 'password');

$allFiles = listAllFiles($ftp, '/public_html/downloads/');

foreach ($allFiles as $file) {
    $local = __DIR__ . '/downloads/' . $file;
    if (!is_dir(dirname($local))) {
        mkdir(dirname($local), 0777, true);
    }
    ftp_get($ftp, $local, '/public_html/downloads/' . $file, FTP_BINARY);
    echo "Downloaded: $file\n";
}

ftp_close($ftp);

This script can recursively obtain all file paths and download them from the /public_html/downloads/ directory of ftp.gitbox.net to the local directory, maintaining the original directory structure.

5. Precautions for debugging and coding

  1. The parsing format is not fixed : the list formats returned by different FTP servers may differ slightly, and flexible regular or split logic should be used when parsing.

  2. Connection and timeout : It is recommended to set reasonable timeout and retry logic to prevent scripts from getting stuck.

  3. Permission check : Make sure the FTP account has permission to read directories and files.

6. Summary

Although the ftp_rawlist() function outputs the original string, through appropriate parsing and logical combination, it is possible to build a powerful command line tool for monitoring, backup and automated management of FTP directories. Whether in daily operation and maintenance or automation scripts, it is a powerful tool worth mastering.