Skip to content

Instantly share code, notes, and snippets.

Forked from Majkl578/gist:2304479
Last active Mar 30, 2017
What would you like to do?

Tiny PHP script to generate static DirectoryIndex

  • With Dark Theme
  • Prompt asking to override, if index.html is already exist
#!/usr/bin/env php
* @author anovsiradj
* @author Michael Moravec
$targetDir = $argc > 1 ? $argv[1] : getcwd();
$targetFile = trim($targetDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'index.html';
if (!is_dir($targetDir)) throw new \InvalidArgumentException("Invalid dir '$targetDir'.");
if (!is_writable($targetDir)) throw new \InvalidArgumentException("Directory '$targetDir' is not writable.");
if (file_exists($targetFile)) {
// throw new \InvalidArgumentException("File '$targetFile' is already exist.");
echo "File '{$targetFile}' is already exist. Override file? ";
$cmd_handle = fopen ("php://stdin", "r");
$cmd_uservoice = strtolower(fgets($cmd_handle));
if(!preg_match('/^(yes|ye|y|1)$/', $cmd_uservoice)) {
echo "Aborting.", PHP_EOL;
$h = fopen($targetFile, 'w');
fwrite($h, '<!doctype html><html><body style="font-family:monospace;color:#eee;background:#222;font-size:1.3em;">');
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, htmlentities($file->getFilename()));
fwrite($h, '</a>');
fwrite($h, '<br>');
fwrite($h, PHP_EOL);
fwrite($h, '<br><small>Generated on: ' . date('c') . '</small></body></html>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment