给你:
$log = '/path/to/your/log.js';
$path = '/path/to/your/dir/with/files/';
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$result = array();
foreach ($files as $file)
{
if (is_file($file = strval($file)) === true)
{
$result[$file] = sprintf('%u|%u', filesize($file), filemtime($file));
}
}
if (is_file($log) !== true)
{
file_put_contents($log, json_encode($result), LOCK_EX);
}
// are there any differences?
if (count($diff = array_diff($result, json_decode(file_get_contents($log), true))) > 0)
{
// send email with mail(), SwiftMailer, PHPMailer, ...
$email = 'The following files have changed:' . "\n" . implode("\n", array_keys($diff));
// update the log file with the new file info
file_put_contents($log, json_encode($result), LOCK_EX);
}
我假设您知道如何发送电子邮件。另外,请记住,$log 文件应保留在您要监视的 $path 之外,当然原因很明显。
第二次阅读您的问题后,我注意到您提到要检查文件是否更改,我只是检查修改的大小和日期,如果你真的想检查文件内容是否不同,我建议你使用文件的哈希,所以这个:
$result[$file] = sprintf('%u|%u', filesize($file), filemtime($file));
变成这样:
$result[$file] = sprintf('%u|%u|%s', filesize($file), filemtime($file), md5_file($file));
// or
$result[$file] = sprintf('%u|%u|%s', filesize($file), filemtime($file), sha1_file($file));
但请记住,这将更加昂贵,因为哈希函数必须打开并读取 1-5 MB CSV 文件的所有内容。