<?php
/**
* Mirrors data from a log file for validation checks.
*
* @param string $logFilePath Path to the log file.
* @param string $mirrorFilePath Path to the destination file for the mirrored data.
* @return bool True on success, false on failure.
*/
function mirrorLogFile(string $logFilePath, string $mirrorFilePath): bool
{
// Check if the log file exists
if (!file_exists($logFilePath)) {
error_log("Log file not found: " . $logFilePath);
return false;
}
// Open the log file for reading
$logFileHandle = fopen($logFilePath, "r");
if (!$logFileHandle) {
error_log("Failed to open log file: " . $logFilePath);
return false;
}
// Open the mirror file for writing
$mirrorFileHandle = fopen($mirrorFilePath, "w");
if (!$mirrorFileHandle) {
error_log("Failed to open mirror file: " . $mirrorFilePath);
fclose($logFileHandle); // Close the log file if mirror file fails to open
return false;
}
try {
// Read the log file line by line
while (($line = fgets($logFileHandle)) !== false) {
// Write each line to the mirror file
fwrite($mirrorFileHandle, $line);
}
} catch (Exception $e) {
error_log("Error reading/writing log file: " . $e->getMessage());
fclose($logFileHandle);
fclose($mirrorFileHandle);
return false;
}
// Close both files
fclose($logFileHandle);
fclose($mirrorFileHandle);
return true;
}
//Example Usage:
//Define the paths to the log file and the mirror file.
$logFile = "my_log.txt";
$mirrorFile = "mirrored_log.txt";
//Call the function.
if (mirrorLogFile($logFile, $mirrorFile)) {
echo "Log file mirrored successfully to " . $mirrorFile . "\n";
} else {
echo "Log file mirroring failed.\n";
}
?>
Add your comment