1. <?php
  2. /**
  3. * Replaces values in a log file for a temporary solution.
  4. *
  5. * @param string $logFilePath Path to the log file.
  6. * @param array $replacements Array of replacements, where key is the value to find and value is the replacement value.
  7. * @return bool True on success, false on failure.
  8. */
  9. function replaceInLogFile(string $logFilePath, array $replacements): bool
  10. {
  11. if (!file_exists($logFilePath)) {
  12. return false; // Log file does not exist
  13. }
  14. $tempFilePath = $logFilePath . '.tmp'; // Create a temporary file
  15. if (file_put_contents($tempFilePath, file_get_contents($logFilePath)) === false) {
  16. return false; // Failed to copy the log file to the temporary file
  17. }
  18. // Perform replacements
  19. foreach ($replacements as $search => $replace) {
  20. $tempContent = file_get_contents($tempFilePath);
  21. $tempContent = str_replace($search, $replace, $tempContent);
  22. file_put_contents($tempFilePath, $tempContent);
  23. }
  24. // Replace the original file with the temporary file
  25. if (unlink($logFilePath) === false && rename($tempFilePath, $logFilePath) === false) {
  26. return false; // Failed to replace the original file
  27. }
  28. return true;
  29. }
  30. // Example usage:
  31. /*
  32. $logFile = 'my_log.txt';
  33. $replacements = [
  34. 'old_value' => 'new_value',
  35. 'another_old' => 'another_new'
  36. ];
  37. if (replaceInLogFile($logFile, $replacements)) {
  38. echo "Log file updated successfully.\n";
  39. } else {
  40. echo "Failed to update log file.\n";
  41. }
  42. */
  43. ?>

Add your comment