Skip to content

Instantly share code, notes, and snippets.

@anovsiradj
Forked from Majkl578/gist:2304479
Last active March 30, 2017 09:01
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 anovsiradj/f3c534f995428c27dc0f1925ad32f611 to your computer and use it in GitHub Desktop.
Save anovsiradj/f3c534f995428c27dc0f1925ad32f611 to your computer and use it in GitHub Desktop.

Tiny PHP script to generate static DirectoryIndex

  • With Dark Theme
  • Prompt asking to override, if index.html is already exist
#!/usr/bin/env php
<?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.");
/*
http://stackoverflow.com/a/15322457/3036312
http://php.net/manual/en/features.commandline.php#94924
*/
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;
exit;
}
}
$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>');
fclose($h);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment