I have an xml file with database information that should be loaded when the script is installed or when the content of the file changes. Can I use md5_file() on the xml file
I know that I am going back in time here, but the question helped me so I want to share what I did with it, so while this is not an answer to the question I will make it a community wiki so it can be improved (I'm no expert).
This was part of a much larger class so I have stripped out the rest and provided just the applicable code and turned it into an easy to follow example using a very common file:
class ApplicationLogger {
private $logfile, $path;
public function __construct() {
$this->logfile = 'error.log';
$this->path = '/var/log/apache2/';
}
public function logState() {
$files = array(
'target' => $this->path . $this->logfile,
'lastmod' => $this->path . $this->logfile . '_lastmod'
);
if (file_exists($files['lastmod']) && file_exists($files['target'])) {
$lfh = fopen($files['lastmod'], 'r');
while (!feof($lfh)) {
$lines[] = fgets($lfh);
}
fclose($lfh);
}
$modified = false;
/**
* check if we have a matching hash.
*/
if (isset($lines) && filemtime($files['target']) != $lines[0]) { // mod time mismatch
if (md5_file($files['target']) != $lines[1]) { // content modified
$modified = true;
}
}
/**
* update or create the lastmod file
*/
if (!file_exists($files['lastmod']) || $modified) {
$current_mod = filemtime($files['target']) . "\n" . md5_file($files['target']);
file_put_contents($files['lastmod'], $current_mod);
$modified = true;
}
return $modified;
}
}
Usage is straight forward:
$mod = new ApplicationLogger();
if ($mod->logState()) {
// changed do something
}
Adapt it to your needs, improve it however you see fit. I hope that you will contribute your adaptations by editing this CW.