1. <?php
  2. /**
  3. * Mirrors data from a log file for validation checks.
  4. *
  5. * @param string $logFilePath Path to the log file.
  6. * @param string $mirrorFilePath Path to the destination file for the mirrored data.
  7. * @return bool True on success, false on failure.
  8. */
  9. function mirrorLogFile(string $logFilePath, string $mirrorFilePath): bool
  10. {
  11. // Check if the log file exists
  12. if (!file_exists($logFilePath)) {
  13. error_log("Log file not found: " . $logFilePath);
  14. return false;
  15. }
  16. // Open the log file for reading
  17. $logFileHandle = fopen($logFilePath, "r");
  18. if (!$logFileHandle) {
  19. error_log("Failed to open log file: " . $logFilePath);
  20. return false;
  21. }
  22. // Open the mirror file for writing
  23. $mirrorFileHandle = fopen($mirrorFilePath, "w");
  24. if (!$mirrorFileHandle) {
  25. error_log("Failed to open mirror file: " . $mirrorFilePath);
  26. fclose($logFileHandle); // Close the log file if mirror file fails to open
  27. return false;
  28. }
  29. try {
  30. // Read the log file line by line
  31. while (($line = fgets($logFileHandle)) !== false) {
  32. // Write each line to the mirror file
  33. fwrite($mirrorFileHandle, $line);
  34. }
  35. } catch (Exception $e) {
  36. error_log("Error reading/writing log file: " . $e->getMessage());
  37. fclose($logFileHandle);
  38. fclose($mirrorFileHandle);
  39. return false;
  40. }
  41. // Close both files
  42. fclose($logFileHandle);
  43. fclose($mirrorFileHandle);
  44. return true;
  45. }
  46. //Example Usage:
  47. //Define the paths to the log file and the mirror file.
  48. $logFile = "my_log.txt";
  49. $mirrorFile = "mirrored_log.txt";
  50. //Call the function.
  51. if (mirrorLogFile($logFile, $mirrorFile)) {
  52. echo "Log file mirrored successfully to " . $mirrorFile . "\n";
  53. } else {
  54. echo "Log file mirroring failed.\n";
  55. }
  56. ?>

Add your comment