Skip to content

Instantly share code, notes, and snippets.

@Majkl578
Created April 4, 2012 18:25
Show Gist options
  • Save Majkl578/2304479 to your computer and use it in GitHub Desktop.
Save Majkl578/2304479 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());
});
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
Copy link

Perfect. Thank you!

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