Skip to content

Instantly share code, notes, and snippets.

@glubo
Forked from Majkl578/gist:2304479
Created April 11, 2012 10:05
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 glubo/2358361 to your computer and use it in GitHub Desktop.
Save glubo/2358361 to your computer and use it in GitHub Desktop.
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());
});
$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