Here's the code..
I needed a simple changelog for one of my PHP projects. So I wrote a function that compares my current sourcecode against the nightly backup I make. This way I can relate support tickets from users to changes in my code and keep things organized.
Here's the code..
<?php
Function Compare($current_sourcepath, $backup_sourcepath) {
if ($handle = opendir($current_sourcepath)) {
/* This is the correct way to loop over the directory. */
$result = '';
$ignore = array(".", "..", "exclude_me.php", "dynamic.php"); // stuff you want excluded
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $ignore)) {
$current_file = $current_sourcepath.$file;
$backup_file = $backup_sourcepath.$file;
$display_file = basename($current_sourcepath.$file, ".php");
// COMPARE
if (!file_exists($backup_file)) $result .= "File added: $display_file<br>";
else {
$current_size = filesize($current_file);
$backup_size = filesize($backup_file);
$size_diff = $backup_size - $current_size;
if ($size_diff != 0) {
$current_lines = count(file($current_file));
$backup_lines = count(file($backup_file));
$lines_diff = $backup_lines - $current_lines;
$result .= "File changed: $display_file ($size_diff bytes / $lines_diff lines)<br>";
}
}
}
}
closedir($handle);
}
return $result;
}
$changes = Compare ("pages/", "backup/pages/");
$changes .= Compare ("modules/", "backup/modules/");
echo "<h1>changelog</h1>$changes";
?>
You could also use file( ... , FILE_SKIP_EMPTY_LINES) because no-one will be interested in empty lines being added.
ReplyDeleteThough, very useful code, thanks for sharing it :)
ReplyDeleteIndeed, if you are not interested in whitespaces being added, you can use the FILE_SKIP_EMPTY_LINES flag.
ReplyDelete