1. <?php
  2. /**
  3. * File Error Detector (Non-Production Use)
  4. *
  5. * Detects potential file errors (permissions, existence) for non-production environments.
  6. */
  7. /**
  8. * Checks if a file exists and is readable.
  9. *
  10. * @param string $filePath The path to the file.
  11. * @return bool True if the file exists and is readable, false otherwise.
  12. */
  13. function isFileReadable(string $filePath): bool
  14. {
  15. if (!file_exists($filePath)) {
  16. return false; // File does not exist
  17. }
  18. if (!is_readable($filePath)) {
  19. return false; // File is not readable
  20. }
  21. return true; // File exists and is readable
  22. }
  23. /**
  24. * Checks if a directory exists and is writable.
  25. *
  26. * @param string $dirPath The path to the directory.
  27. * @return bool True if the directory exists and is writable, false otherwise.
  28. */
  29. function isDirectoryWritable(string $dirPath): bool
  30. {
  31. if (!is_dir($dirPath)) {
  32. return false; // Directory does not exist
  33. }
  34. if (!is_writable($dirPath)) {
  35. return false; // Directory is not writable
  36. }
  37. return true; // Directory exists and is writable
  38. }
  39. /**
  40. * Detects file errors in a given directory.
  41. *
  42. * @param string $directoryPath The path to the directory to check.
  43. * @return array An array of errors found. Empty array if no errors.
  44. */
  45. function detectFileErrors(string $directoryPath): array
  46. {
  47. $errors = [];
  48. if (!is_dir($directoryPath)) {
  49. $errors[] = "Error: Directory '$directoryPath' does not exist.";
  50. return $errors;
  51. }
  52. $files = scandir($directoryPath);
  53. if ($files === false) {
  54. $errors[] = "Error: Could not scan directory '$directoryPath'.";
  55. return $errors;
  56. }
  57. foreach ($files as $file) {
  58. if ($file == '.' || $file == '..') {
  59. continue; // Skip current and parent directory entries
  60. }
  61. $filePath = $directoryPath . '/' . $file;
  62. if (!isFileReadable($filePath)) {
  63. $errors[] = "Error: File '$filePath' is not readable.";
  64. }
  65. if (is_file($filePath) && !is_readable($filePath)) {
  66. $errors[] = "Error: File '$filePath' is not readable.";
  67. }
  68. }
  69. return $errors;
  70. }
  71. // Example Usage (for testing/non-production)
  72. if (php_sapi_name() !== 'cli') {
  73. // Prevent execution when running from command line
  74. exit;
  75. }
  76. $directoryToScan = './uploads'; // Replace with your directory
  77. $errors = detectFileErrors($directoryToScan);
  78. if (empty($errors)) {
  79. echo "No file errors detected in '$directoryToScan'.\n";
  80. } else {
  81. echo "File errors detected in '$directoryToScan':\n";
  82. foreach ($errors as $error) {
  83. echo "- " . $error . "\n";
  84. }
  85. }
  86. ?>

Add your comment