php 8.6比较目录变化时,可以先为受信静态目录生成相对路径到sha-256的映射,再比较两次清单,分别得到新增、删除和内容变化。目录遍历与哈希不是原子快照,应在写入暂停或稳定副本上执行,不能把边读边改的目录当成一致数据集。

PHP手册中的RecursiveIteratorIterator::__construct
生成清单并与上一份作比较
<?php
function snapshot(string $directory): array {
$root=realpath($directory);
if ($root===false || !is_dir($root)) throw new RuntimeException('目录不存在');
$out=[];
$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
$root,FilesystemIterator::SKIP_DOTS
));
foreach ($it as $file) {
if ($file->isLink() || !$file->isFile()) continue;
if (count($out)>=10000 || $file->getSize()>50*1024*1024) {
throw new RuntimeException('超出快照预算');
}
$name=substr($file->getPathname(),strlen($root)+1);
$hash=hash_file('sha256',$file->getPathname());
if ($hash===false) throw new RuntimeException('文件读取失败');
$out[$name]=$hash;
}
ksort($out,SORT_STRING); return $out;
}
$base='/srv/app-private/snapshot.json';
$current=snapshot('/srv/app-private/documents');
if (is_file($base)) {
$old=json_decode(file_get_contents($base),true,512,JSON_THROW_ON_ERROR);
if (!is_array($old)) throw new RuntimeException('旧快照格式不符');
$added=array_keys(array_diff_key($current,$old));
$deleted=array_keys(array_diff_key($old,$current)); $changed=[];
foreach (array_intersect_key($current,$old) as $name=>$hash) {
if ($old[$name]!==$hash) $changed[]=$name;
}
echo json_encode(compact('added','deleted','changed'),JSON_THROW_ON_ERROR),"\n";
} else {
$json=json_encode($current,JSON_THROW_ON_ERROR|JSON_PRETTY_PRINT);
if (file_put_contents($base,$json,LOCK_EX)!==strlen($json)) {
throw new RuntimeException('基线保存失败');
}
echo "已建立基线\n";
}
PHP手册中的hash_file
基线不能在比对后自动覆盖
第一次建立基线,后续运行只报告差异;确认变更合法后,再由明确的发布或审核步骤替换基线。快照文件应保存在被扫描目录之外,并限制修改权限。代码没有把任何差异自动删除或回滚。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
说明清单能证明什么
未启用FOLLOW_SYMLINKS,遇到符号链接跳过。比较按相对路径进行,文件改名会表现为删除加新增,不自动推断重命名。SHA-256比较内容,不覆盖所有者、权限和扩展属性;文件读失败时整次结果失败,而不是输出一份看似完整的部分清单。


















