-
-
Save glubo/2358361 to your computer and use it in GitHub Desktop.
Tiny php script to generate simple directory index.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/php | |
<?php | |
/** | |
* @author Michael Moravec | |
*/ | |
$targetDir = $argc > 1 ? $argv[1] : getcwd(); | |
if (!is_dir($targetDir)) throw new \InvalidArgumentException("Invalid dir '$targetDir'."); | |
if (!is_writable($targetDir)) throw new \InvalidArgumentException("Directory '$targetDir' is not writable."); | |
$h = fopen($targetDir . DIRECTORY_SEPARATOR . 'index.html', 'w'); | |
fwrite($h, '<!doctype html>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '<html>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '<body>'); | |
fwrite($h, PHP_EOL); | |
$files = iterator_to_array(new \CallbackFilterIterator(new \FilesystemIterator($targetDir), function ($item) { | |
return $item->isFile() && $item->getFilename() !== 'index.html'; | |
})); | |
usort($files, function ($a, $b) { | |
return strcmp($a->getFilename(), $b->getFilename()); | |
}); | |
$template = '<a href="%s">%s</a>'.PHP_EOL.'<br>'.PHP_EOL; | |
foreach ($files as $file) { | |
$href = htmlspecialchars(rawurlencode($file->getFilename())) | |
$label = htmlspecialchars($file->getFilename(); | |
$line = sprintf($template, $href, $label); | |
fwrite($h, $line); | |
} | |
fwrite($h, '<br>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '<br>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '<small>Generated on: '); | |
fwrite($h, (new \DateTime())->format('d.m.Y H:i:s')); | |
fwrite($h, '</small>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '</body>'); | |
fwrite($h, PHP_EOL); | |
fwrite($h, '</html>'); | |
fclose($h); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment