Current Location: Home> Latest Articles> Use ftp_rawlist to get daily update files in a timed task

Use ftp_rawlist to get daily update files in a timed task

gitbox 2025-05-26

Scene introduction

Suppose we have a remote FTP server that updates files every day. Our goal is to automatically connect to the server through PHP scripts in the early hours of every morning, check which files are newly uploaded that day, and then download these files locally for subsequent processing.

Step 1: Connect to the FTP server

First, we need to connect to the FTP server and log in:

 $ftp_host = 'ftp.gitbox.net';
$ftp_user = 'username';
$ftp_pass = 'password';

$conn_id = ftp_connect($ftp_host);
if (!$conn_id) {
    die("Unable to connect to FTP server");
}

$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
if (!$login_result) {
    ftp_close($conn_id);
    die("FTP Login failed");
}

Step 2: Get the directory list

Use ftp_rawlist to get file information in the target directory:

 $remote_dir = '/updates/';
$raw_list = ftp_rawlist($conn_id, $remote_dir);
if ($raw_list === false) {
    ftp_close($conn_id);
    die("Unable to get file list");
}

Step 3: Parsing the file list

ftp_rawlist returns a set of lines similar to the output of the Unix ls -l command. We need to parse these lines, extract the file name and modify the time:

 $today = date('M d'); // e.g., "May 23"
$files_to_download = [];

foreach ($raw_list as $line) {
    $parts = preg_split("/\s+/", $line, 9);
    if (count($parts) < 9) continue;

    $month = $parts[5];
    $day = str_pad($parts[6], 2, '0', STR_PAD_LEFT);
    $file_time_or_year = $parts[7];
    $name = $parts[8];

    if ("$month $day" == $today) {
        $files_to_download[] = $name;
    }
}

Step 4: Download the file

Then download the updated files on that day:

 foreach ($files_to_download as $file) {
    $local_file = __DIR__ . "/downloads/$file";
    $remote_file = $remote_dir . $file;
    if (ftp_get($conn_id, $local_file, $remote_file, FTP_BINARY)) {
        echo "Download the file successfully:$file\n";
    } else {
        echo "Download failed:$file\n";
    }
}

Step 5: Close the connection

After the task is completed, close the FTP connection:

 ftp_close($conn_id);

Summarize

Through the above steps, we implement a PHP-based timing task script that can automatically connect to the FTP server and download daily updated files. This script can be run regularly every day with Linux's cron timing task system without manual intervention. This method is suitable for a variety of scenarios where files need to be updated regularly, especially when dealing with log files, data synchronization, or static resource updates.