<?php
/**
* Replaces values in a log file for a temporary solution.
*
* @param string $logFilePath Path to the log file.
* @param array $replacements Array of replacements, where key is the value to find and value is the replacement value.
* @return bool True on success, false on failure.
*/
function replaceInLogFile(string $logFilePath, array $replacements): bool
{
if (!file_exists($logFilePath)) {
return false; // Log file does not exist
}
$tempFilePath = $logFilePath . '.tmp'; // Create a temporary file
if (file_put_contents($tempFilePath, file_get_contents($logFilePath)) === false) {
return false; // Failed to copy the log file to the temporary file
}
// Perform replacements
foreach ($replacements as $search => $replace) {
$tempContent = file_get_contents($tempFilePath);
$tempContent = str_replace($search, $replace, $tempContent);
file_put_contents($tempFilePath, $tempContent);
}
// Replace the original file with the temporary file
if (unlink($logFilePath) === false && rename($tempFilePath, $logFilePath) === false) {
return false; // Failed to replace the original file
}
return true;
}
// Example usage:
/*
$logFile = 'my_log.txt';
$replacements = [
'old_value' => 'new_value',
'another_old' => 'another_new'
];
if (replaceInLogFile($logFile, $replacements)) {
echo "Log file updated successfully.\n";
} else {
echo "Failed to update log file.\n";
}
*/
?>
Add your comment