Current Location: Home> Latest Articles> Implement FTP directory snapshot comparison function through ftp_rawlist

Implement FTP directory snapshot comparison function through ftp_rawlist

gitbox 2025-05-26

In daily operation and maintenance or website management, we often encounter a need: monitor whether a directory file on the FTP server has been added, modified or deleted. Although it can be implemented using file synchronization tools or advanced monitoring systems, if we want to implement directory snapshot comparison in a lighter and more flexible way, the ftp_rawlist function provided by PHP is a very practical solution.

1. What is ftp_rawlist?

ftp_rawlist is one of the FTP operation functions provided by PHP, which allows us to get the original directory list of remote directories. Compared with ftp_nlist that only returns file names, ftp_rawlist returns detailed information similar to the output of Unix ls -l command, including permissions, file size, timestamps, etc.

By comparing the ftp_rawlist results captured at two points in time, we can easily achieve "directory snapshot" comparison and identify which files have changed.

2. Brief description of the implementation logic

  1. Connect to the FTP server and log in

  2. Crawl the file list of the target directory (i.e., snapshot)

  3. Save snapshots to local file

  4. Recrawl on next run and compare with the last snapshot

  5. Output changes (add, delete, modify)

3. PHP implementation example

Here is a complete PHP script example that demonstrates how to grab an FTP snapshot and compare it to the last snapshot:

<code> ```php <?php

// FTP configuration
$ftp_host = "ftp.gitbox.net";
$ftp_user = "ftp_user";
$ftp_pass = "ftp_password";
$ftp_dir = "/htdocs/";
$snapshot_file = DIR . '/last_snapshot.txt';

// Connect and log in
$conn = ftp_connect($ftp_host);
if (!$conn) {
die("Cannot connect to FTP server");
}
if (!ftp_login($conn, $ftp_user, $ftp_pass)) {
ftp_close($conn);
die("FTP login failed");
}

// Get the current snapshot
ftp_chdir($conn, $ftp_dir);
$rawlist = ftp_rawlist($conn, ".");
ftp_close($conn);

// parse snapshots into structured arrays
function parse_rawlist($rawlist) {
$snapshot = [];
foreach ($rawlist as $line) {
$parts = preg_split("/\s+/", $line, 9);
if (count($parts) < 9) continue;
$name = $parts[8];
$info = [
'perm' => $parts[0],
'size' => $parts[4],
'date' => "{$parts[5]} {$parts[6]} {$parts[7]}"
];
$snapshot[$name] = $info;
}
return $snapshot;
}

$current_snapshot = parse_rawlist($rawlist);

// Load the last snapshot
$previous_snapshot = file_exists($snapshot_file) ? unserialize(file_get_contents($snapshot_file)) : [];

// Comparison snapshots
$added = array_diff_key($current_snapshot, $previous_snapshot);
$deleted = array_diff_key($previous_snapshot, $current_snapshot);
$modified = [];

foreach ($current_snapshot as $file => $info) {
if (isset($previous_snapshot[$file])) {
if ($info['size'] !== $previous_snapshot[$file]['size'] ||
$info['date'] !== $previous_snapshot[$file]['date']) {
$modified[$file] = $info;
}
}
}

// Output change results
echo "=== File Change Report===\n";

if ($added) {
echo "\n[New File]:\n";
foreach ($added as $file => $info) {
echo " + $file\n";
}
}

if ($deleted) {
echo "\n[Delete File]:\n";
foreach ($deleted as $file => $info) {
echo " - $file\n";
}
}

if ($modified) {
echo "\n[Modify file]:\n";
foreach ($modified as $file => $info) {
echo " * $file\n";
}
}

// Save the current snapshot
file_put_contents($snapshot_file, serialize($current_snapshot));

 </code>

## Four、Practical suggestions

1. **Timed execution**:Available `cron` or Windows Mission planning hourly/Run the script once a day,Generate snapshots regularly。
2. **Notification mechanism**:可以将变动信息pass邮件orWebhookSend notifications,Get informed of risk operations in a timely manner。
3. **Filtering rules**:脚本中可加入白名单or忽略规则,For example, skip `.log`、`.tmp` document。

## five、Summarize

pass `ftp_rawlist` Get the original directory structure,Structured、Serialization and comparison,We can achieve similar costs at a very small cost“Directory monitoring”Functions。This method is especially suitable for small projects、Old system、or仅需临时监控的场景。Save resources,Flexible and efficient,yesPHPA practical use in lightweight automation“Black Technology”。