1. <?php
  2. /**
  3. * Error Handling and Fallback for File Operations
  4. *
  5. * Wraps file operations with error handling and fallback mechanisms.
  6. *
  7. * @param string $filePath Path to the file.
  8. * @param string $operation The operation to perform (e.g., 'read', 'write').
  9. * @param string $fallback_data Data to use if the primary operation fails.
  10. * @return mixed|false The result of the operation, or false on failure.
  11. */
  12. function safeFileOperation(string $filePath, string $operation, string $fallback_data = ''): mixed
  13. {
  14. try {
  15. switch ($operation) {
  16. case 'read':
  17. $fileContent = file_get_contents($filePath);
  18. if ($fileContent === false) {
  19. // Fallback: Return default data if file read fails
  20. error_log("Error reading file: $filePath. Falling back to: $fallback_data");
  21. return $fallback_data;
  22. }
  23. return $fileContent;
  24. case 'write':
  25. $result = file_put_contents($filePath, $fallback_data);
  26. if ($result === false) {
  27. error_log("Error writing to file: $filePath. Falling back to: $fallback_data");
  28. return false; // Indicate failure
  29. }
  30. return $result;
  31. case 'exists':
  32. if (file_exists($filePath)) {
  33. return true;
  34. } else {
  35. error_log("File does not exist: $filePath");
  36. return false;
  37. }
  38. default:
  39. error_log("Unsupported file operation: $operation");
  40. return false;
  41. }
  42. } catch (Exception $e) {
  43. error_log("Unexpected error: " . $e->getMessage());
  44. return false;
  45. }
  46. }
  47. // Example Usage:
  48. // $content = safeFileOperation('my_file.txt', 'read', 'Default content');
  49. // if ($content !== false) {
  50. // echo $content;
  51. // }
  52. // $result = safeFileOperation('new_file.txt', 'write', 'Initial data');
  53. // if ($result === false) {
  54. // echo "Write failed!";
  55. // }
  56. ?>

Add your comment