So for reasons I’m not going to go into, today I had to compare some log files. I was tempted to write the code in C, just because I miss it so much these days x.x;, but laziness won out, especially as there weren’t that many log files and they weren’t that large, so I wrote it in PHP.
Nothing else to this post except the working code which took me about 5 minutes to type out... The function goes through one directory and all of its subdirectories and checks all files against the same path in a second directory. If the file doesn’t exist in the second directory or its contents doesn’t match the first file up to the first file’s length, a message is outputted.
//Start the log run against 2 root directories
TestLogs("/DIR1", "/DIR2");
function TestLogs($RootDir1, $RootDir2, $CurDir="")
{
//Iterate through the first directory
$Dir1=opendir("$RootDir1$CurDir");
$SubDirs=Array(); //Holds subdirectories
while($File=readdir($Dir1))
if($File=="." || $File=="..") //Skip . and ..
continue;
else if(is_dir("$RootDir1$CurDir/$File")) //Do not try to compare directory entries
$SubDirs[]=$File; //Remember subdirectories
else if(!file_exists("$RootDir2$CurDir/$File"))
print "File '$CurDir/$File' does not exist in second directory.
";
else if(file_get_contents("$RootDir1$CurDir/$File")!=substr(file_get_contents("$RootDir2$CurDir/$File"),0,filesize("$RootDir1$CurDir/$File"))) //Both files exist, so compare them - if first file does not equal second file up to the same length, output error
print "'$CurDir/$File' does not match.
";
//Run subdirectories recursively after current directories' file-run so directories do not get split up
foreach($SubDirs as $NewDir)
TestLogs($RootDir1, $RootDir2, "$CurDir/$NewDir");
}