1. <?php
  2. /**
  3. * Hashes log stream values for batch processing.
  4. *
  5. * @param string $logStreamPath Path to the log file.
  6. * @param string $hashAlgorithm The hashing algorithm to use (e.g., 'sha256').
  7. * @param string $outputFile Path to the output file for hashed values.
  8. * @return void
  9. */
  10. function hashLogStream(string $logStreamPath, string $hashAlgorithm, string $outputFile): void
  11. {
  12. try {
  13. // Open the log file for reading.
  14. $logFile = fopen($logStreamPath, 'r');
  15. if (!$logFile) {
  16. error_log("Error: Could not open log file: $logStreamPath");
  17. return;
  18. }
  19. // Open the output file for writing.
  20. $outputFileHandle = fopen($outputFile, 'w');
  21. if (!$outputFileHandle) {
  22. error_log("Error: Could not open output file: $outputFile");
  23. fclose($logFile);
  24. return;
  25. }
  26. // Process each line in the log file.
  27. while (($line = fgets($logFile)) !== false) {
  28. // Skip empty lines.
  29. if (empty($line)) {
  30. continue;
  31. }
  32. // Hash the log line.
  33. $hash = hash($hashAlgorithm, $line);
  34. // Write the original line and its hash to the output file.
  35. fprintf($outputFileHandle, "%s|%s\n", $line, $hash);
  36. }
  37. // Close the log file and the output file.
  38. fclose($logFile);
  39. fclose($outputFileHandle);
  40. echo "Log stream hashed successfully. Hashed values written to: $outputFile\n";
  41. } catch (Exception $e) {
  42. error_log("An unexpected error occurred: " . $e->getMessage());
  43. }
  44. }
  45. // Example usage:
  46. // hashLogStream('/path/to/your/log.txt', 'sha256', '/path/to/hashed_logs.txt');
  47. ?>

Add your comment