Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // NOTE: this script will overwrite index.html files so be careful.
- //
- // Save as generate.php
- // Call as:
- // php -f generate.php /some/dir
- // Only run from the commandline
- if (!php_sapi_name() == "cli") {
- exit('Access denied.' . PHP_EOL);
- }
- // Check if the root directory was passed to us on the commandline
- if ($argc < 2) {
- exit('Commandline param missing (root directory path)' . PHP_EOL);
- }
- $root_dir = $argv[1];
- // Check if the root dir exists and is a directory
- if (!is_dir($root_dir)) {
- exit('Not a directory: ' . $root_dir . PHP_EOL);
- }
- // Generate the html files with directory contents
- generateDirContents($root_dir);
- // Loops through a directory and generates an index.html file
- // with the directory contents
- function generateDirContents($rootDir){
- $filesOrDirs = scandir($rootDir);
- // Build an array with files and an array with directories
- $files = array();
- $dirs = array();
- foreach($filesOrDirs as $key => $value){
- $path = realpath($rootDir.DIRECTORY_SEPARATOR.$value);
- if(!is_dir($path)) {
- $files[] = $path;
- } else if($value != "." && $value != "..") {
- // recursively call ourselves for sub directories
- generateDirContents($path);
- $dirs[] = $path;
- }
- }
- // generate the html
- $html = generateHtml($rootDir, $files, $dirs);
- // write the html into an index.html file
- $htmlFile = $rootDir . DIRECTORY_SEPARATOR . 'index.html';
- file_put_contents($htmlFile, $html);
- }
- // Main function to generate the html
- function generateHtml($rootDir, $files, $dirs) {
- $html = getHeader($rootDir);
- foreach($dirs as $dir) {
- $html .= getDirHtml($dir);
- }
- foreach($files as $file) {
- $html .= getFileHtml($file);
- }
- $html .= getFooter($rootDir);
- return $html;
- }
- // Html snippet for each directory
- function getDirHtml($dir) {
- $html = <<< EOT
- <div class="dir">$dir</div>
- EOT;
- return $html;
- }
- // Html snippet for each file
- function getFileHtml($file) {
- $html = <<< EOT
- <div class="file">$file</div>
- EOT;
- return $html;
- }
- // Html snippet for the header
- function getHeader($rootDir) {
- $html = <<< EOT
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title>$rootDir</title>
- </head>
- <body>
- <p>header</p>
- EOT;
- return $html;
- }
- // Html snippet for the footer
- function getFooter($rootDir) {
- $html = <<< EOT
- <p>footer</p>
- </body>
- </html>
- EOT;
- return $html;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement