Skip to content

Instantly share code, notes, and snippets.

@divinity76
Last active April 9, 2024 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divinity76/9d28de7f0704cb6b93507e390a7f05cd to your computer and use it in GitHub Desktop.
Save divinity76/9d28de7f0704cb6b93507e390a7f05cd to your computer and use it in GitHub Desktop.
autoindex php
<?php
declare(strict_types=1);
/**
* returns a plain string array of path to all files in a directory, and subdirectories,
* but does not return directories themselves. (meaning if a directory is empty, it will not be included at all)
*
* @param string $dir
* @param bool $realpath
* @throws UnexpectedValueException if $dir is not readable/does not exists
* @return string[] files
*/
function get_file_list_recursively(string $dir, bool $realpath = false): array
{
$files = array();
$files = [];
foreach ((new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS))) as $file) {
/** @var SplFileInfo $file */
if ($realpath) {
$files[] = $file->getRealPath();
} else {
$files[] = $file->getPathname();
}
}
return $files;
}
function tohtml(string $str): string
{
return htmlentities($str, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE | ENT_DISALLOWED, 'UTF-8', true);
}
chdir(__DIR__);
$files = get_file_list_recursively(".");
//$files = array_reverse($files);
sort($files,SORT_NATURAL);
//rsort($files);
$html = '';
foreach ($files as $filepath) {
$filepath = str_replace("\\", "/", $filepath);
if (str_starts_with($filepath, "./")) {
$filepath = substr($filepath, strlen("./"));
}
$str = "<a href=\"" . tohtml(($filepath)) . "\">" . tohtml($filepath) . "</a><br>\n";
$html .= $str;
}
echo $html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment