user715564
user715564

Reputation: 1690

How to check if file hash has changed with php

I have a php script that saves the file names of every file in directory to text file. That text file is then hashed. Here are the lines in my script:

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

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

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

echo $md5file;

If a new file is uploaded, removed, or a file name is changed then the hash will change. I need a way to check and see if that hash has changed or not.

Upvotes: 1

Views: 1995

Answers (2)

Dave Cartwright
Dave Cartwright

Reputation: 358

2 possibilities without a DB:

  • make a second file and save the last filename in it and compare against it.
  • include the file size into the filename or head of file and check if the file size has changed.

Upvotes: 0

Stoic
Stoic

Reputation: 10754

A dirty way (without using database) would be:

$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.. 
}

Basically, I am storing the current hash to a particular file, and reading this file on the next iteration. If the hash has changed, I store the new hash to this file for comparison later on, and voila!

Note that, the same can be performed over database, if you are using one.

Upvotes: 2

Related Questions