<?php
/**
* Limits directory listing output for a one-off script.
*
* Prevents excessive output when listing directories,
* particularly in cases with many files.
*
* @param string $dir The directory to list.
* @param int $max_files The maximum number of files to display. Defaults to 20.
*/
function limitDirectoryListing(string $dir, int $max_files = 20): void
{
// Check if the directory exists
if (!is_dir($dir)) {
echo "Directory not found.\n";
return;
}
$files = scandir($dir);
if ($files === false) {
echo "Error reading directory.\n";
return;
}
$count = 0;
foreach ($files as $file) {
// Skip current and parent directories
if ($file == "." || $file == "..") {
continue;
}
// Only output the first $max_files files
if ($count < $max_files) {
echo $file . "\n";
$count++;
} else {
break; // Stop iterating once the limit is reached
}
}
}
// Example usage:
// limitDirectoryListing("/path/to/your/directory", 10);
?>
Add your comment