<?php
/**
* Error Handling and Fallback for File Operations
*
* Wraps file operations with error handling and fallback mechanisms.
*
* @param string $filePath Path to the file.
* @param string $operation The operation to perform (e.g., 'read', 'write').
* @param string $fallback_data Data to use if the primary operation fails.
* @return mixed|false The result of the operation, or false on failure.
*/
function safeFileOperation(string $filePath, string $operation, string $fallback_data = ''): mixed
{
try {
switch ($operation) {
case 'read':
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
// Fallback: Return default data if file read fails
error_log("Error reading file: $filePath. Falling back to: $fallback_data");
return $fallback_data;
}
return $fileContent;
case 'write':
$result = file_put_contents($filePath, $fallback_data);
if ($result === false) {
error_log("Error writing to file: $filePath. Falling back to: $fallback_data");
return false; // Indicate failure
}
return $result;
case 'exists':
if (file_exists($filePath)) {
return true;
} else {
error_log("File does not exist: $filePath");
return false;
}
default:
error_log("Unsupported file operation: $operation");
return false;
}
} catch (Exception $e) {
error_log("Unexpected error: " . $e->getMessage());
return false;
}
}
// Example Usage:
// $content = safeFileOperation('my_file.txt', 'read', 'Default content');
// if ($content !== false) {
// echo $content;
// }
// $result = safeFileOperation('new_file.txt', 'write', 'Initial data');
// if ($result === false) {
// echo "Write failed!";
// }
?>
Add your comment