如何使用php检查文件哈希是否已更改

时间:2013-12-19 22:05:40

标签: php hash

我有一个php脚本,可以将目录中每个文件的文件名保存到文本文件中。然后对该文本文件进行哈希处理。以下是我脚本中的行:

$allnames = implode(",", $fileslist);

file_put_contents($post_dir . "/md5file.txt",$allnames);

$md5file = md5_file($post_dir . "/md5file.txt");

echo $md5file;

如果上传,删除新文件或更改文件名,则哈希值将更改。我需要一种方法来检查并查看该哈希是否已更改。

2 个答案:

答案 0 :(得分:2)

一种肮脏的方式(不使用数据库)将是:

$allnames = implode(",", $fileslist);
file_put_contents($post_dir . "/md5file.txt",$allnames);
$md5file = md5_file($post_dir . "/md5file.txt");
$last_hash = file_get_contents($post_dir . "/last_hash.txt");

if ($md5file != $last_hash) {
  // save the new hash
  file_out_contents($post_dir . "/last_hash.txt", $md5file);
  // some file may have been added, removed or rename
  // do something..
} else {
  // no files has been added, removed or renamed, since last change.
  // do something.. 
}

基本上,我将当前哈希存储到特定文件,并在下一次迭代中读取此文件。如果散列已更改,我会将新散列存储到此文件中以供稍后进行比较,并且瞧!

请注意,如果您使用的话,可以在数据库上执行相同的操作。

答案 1 :(得分:0)

没有数据库的2种可能性:

  • 制作第二个文件并保存最后一个文件名并与之进行比较。
  • 将文件大小包含在文件名或文件头中,并检查文件大小是否已更改。
相关问题