1. <?php
  2. /**
  3. * Limits directory listing output for a one-off script.
  4. *
  5. * Prevents excessive output when listing directories,
  6. * particularly in cases with many files.
  7. *
  8. * @param string $dir The directory to list.
  9. * @param int $max_files The maximum number of files to display. Defaults to 20.
  10. */
  11. function limitDirectoryListing(string $dir, int $max_files = 20): void
  12. {
  13. // Check if the directory exists
  14. if (!is_dir($dir)) {
  15. echo "Directory not found.\n";
  16. return;
  17. }
  18. $files = scandir($dir);
  19. if ($files === false) {
  20. echo "Error reading directory.\n";
  21. return;
  22. }
  23. $count = 0;
  24. foreach ($files as $file) {
  25. // Skip current and parent directories
  26. if ($file == "." || $file == "..") {
  27. continue;
  28. }
  29. // Only output the first $max_files files
  30. if ($count < $max_files) {
  31. echo $file . "\n";
  32. $count++;
  33. } else {
  34. break; // Stop iterating once the limit is reached
  35. }
  36. }
  37. }
  38. // Example usage:
  39. // limitDirectoryListing("/path/to/your/directory", 10);
  40. ?>

Add your comment