1. <?php
  2. /**
  3. * Reads text data from a file, with fallback mechanisms and error handling.
  4. *
  5. * @param string $filePath The path to the text file.
  6. * @param string $fallbackData Optional data to use if the file read fails.
  7. * @return string|null The content of the file, or the fallback data if the file is unavailable, or null on critical error.
  8. */
  9. function readTextFileWithFallback(string $filePath, string $fallbackData = ''): ?string
  10. {
  11. try {
  12. // Attempt to read the file.
  13. $fileContent = file_get_contents($filePath);
  14. // Check if file read was successful.
  15. if ($fileContent === false) {
  16. // File read failed. Log an error (or perform other logging).
  17. error_log("Error reading file: " . $filePath);
  18. return $fallbackData; // Use fallback data.
  19. }
  20. return $fileContent; // Return the file content.
  21. } catch (Exception $e) {
  22. //Catch any unexpected exceptions.
  23. error_log("Unexpected error reading file: " . $filePath . " - " . $e->getMessage());
  24. return $fallbackData;
  25. }
  26. }
  27. // Example usage:
  28. $filePath = 'data.txt'; // Replace with your file path
  29. $fallbackData = "Default data in case of file failure.";
  30. $data = readTextFileWithFallback($filePath, $fallbackData);
  31. if ($data !== null) {
  32. echo "File content:\n" . $data . "\n";
  33. } else {
  34. echo "Failed to retrieve data from file.\n";
  35. }
  36. ?>

Add your comment