Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tiny php script to generate simple directory index.
#!/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());
});
foreach ($files as $file) {
fwrite($h, '<a href="');
fwrite($h, htmlspecialchars(rawurlencode($file->getFilename())));
fwrite($h, '">');
fwrite($h, htmlspecialchars($file->getFilename()));
fwrite($h, '</a>');
fwrite($h, PHP_EOL);
fwrite($h, '<br>');
fwrite($h, PHP_EOL);
}
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);
@anovsiradj

This comment has been minimized.

Copy link

@anovsiradj anovsiradj commented Feb 14, 2017

Perfect. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment