1. <?php
  2. /**
  3. * Extends existing text file logic with debugging and input validation.
  4. *
  5. * @param string $filename The name of the text file.
  6. * @param array $data The data to write to the file.
  7. * @param string $mode The file opening mode (e.g., 'w', 'a').
  8. * @return bool True on success, false on failure.
  9. */
  10. function writeDataToFileWithDebug(string $filename, array $data, string $mode = 'w'): bool
  11. {
  12. // Input validation: Check if filename is provided and is a string.
  13. if (empty($filename) || !is_string($filename)) {
  14. error_log("Invalid filename provided: " . var_export($filename, true));
  15. return false;
  16. }
  17. //Input validation: Check if data is provided and is an array
  18. if(empty($data) || !is_array($data)){
  19. error_log("Invalid data provided: " . var_export($data, true));
  20. return false;
  21. }
  22. // Debugging: Log the filename and data being written.
  23. error_log("Writing to file: " . $filename);
  24. error_log("Data to write: " . json_encode($data));
  25. try {
  26. $result = file_put_contents($filename, json_encode($data)); //Use json_encode to handle arrays properly
  27. if ($result === false) {
  28. error_log("Error writing to file: " . $filename);
  29. return false;
  30. }
  31. return true;
  32. } catch (Exception $e) {
  33. error_log("Exception writing to file: " . $e->getMessage());
  34. return false;
  35. }
  36. }
  37. /**
  38. * Reads data from a text file with basic validation.
  39. *
  40. * @param string $filename The name of the text file.
  41. * @return array|false The data read from the file as an array, or false on failure.
  42. */
  43. function readDataFromFileWithDebug(string $filename): array|false
  44. {
  45. // Input validation: Check if filename is provided and is a string
  46. if (empty($filename) || !is_string($filename)) {
  47. error_log("Invalid filename provided: " . var_export($filename, true));
  48. return false;
  49. }
  50. // Debugging: Log the filename being read.
  51. error_log("Reading from file: " . $filename);
  52. try {
  53. $file_contents = file_get_contents($filename);
  54. if ($file_contents === false) {
  55. error_log("Error reading file: " . $filename);
  56. return false;
  57. }
  58. $data = json_decode($file_contents, true); // Decode JSON to array
  59. if (json_last_error() !== JSON_ERROR_NONE) {
  60. error_log("Error decoding JSON from file: " . $filename . ". Error: " . json_last_error_msg());
  61. return false;
  62. }
  63. return $data;
  64. } catch (Exception $e) {
  65. error_log("Exception reading from file: " . $e->getMessage());
  66. return false;
  67. }
  68. }
  69. ?>

Add your comment