1. <?php
  2. /**
  3. * Imports data from a text file, performing defensive checks.
  4. *
  5. * @param string $filePath Path to the text file.
  6. * @param string $delimiter Delimiter used in the text file (default: comma).
  7. * @param bool $skipHeader Whether to skip the first line (header) (default: false).
  8. * @return array|false An array of data rows, or false on error.
  9. */
  10. function importTextFile(string $filePath, string $delimiter = ',', bool $skipHeader = false): array|false
  11. {
  12. if (!file_exists($filePath)) {
  13. error_log("File not found: $filePath");
  14. return false; // File does not exist
  15. }
  16. if (!is_readable($filePath)) {
  17. error_log("File not readable: $filePath");
  18. return false; // File is not readable
  19. }
  20. $data = [];
  21. $headerSkipped = false;
  22. if (($handle = fopen($filePath, 'r')) !== false) {
  23. while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
  24. if (!$headerSkipped) {
  25. $headerSkipped = true;
  26. continue; // Skip the header row
  27. }
  28. // Defensive check: Ensure row has the expected number of columns.
  29. if (count($row) < 1) {
  30. error_log("Skipping row with insufficient columns: " . implode(',', $row));
  31. continue;
  32. }
  33. //Data validation example - check if a required field is not empty
  34. if (empty($row[0])) {
  35. error_log("Skipping row with empty required field (column 0): " . implode(',', $row));
  36. continue;
  37. }
  38. $data[] = $row;
  39. }
  40. fclose($handle);
  41. } else {
  42. error_log("Failed to open file: $filePath");
  43. return false; // File opening failed
  44. }
  45. return $data;
  46. }
  47. //Example Usage:
  48. // $data = importTextFile('data.txt', ',', true);
  49. // if ($data !== false) {
  50. // print_r($data);
  51. // }
  52. ?>

Add your comment