1

Below is the php script I found to dynamically generate links to files present in current directory. can anyone of u help me with php script to dynamically generate links to all the directory ,sub-directory and files present in the root directory.

<?php
$dir_open = opendir('.');

while(false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $link = "<a href='./$filename'> $filename </a><br />";
        echo $link;
    }
}

closedir($dir_open);
?>

3 Answers3

0

Try this:

** UPDATE ** To show file name instead of the full path

<?php
$directory = new \RecursiveDirectoryIterator($path);
$iterator = new \RecursiveIteratorIterator($directory);
$files = array();
foreach ($iterator as $info) {
    echo  '<a href="' . $info->getFilename() . '">' . $info->getFilename() . '</a><br />';    
}
lloiacono
  • 4,714
  • 2
  • 30
  • 46
  • hey this displays the entire path. i just want it to display the directory name, can u help me modify the code. – Shesha Chandrika May 03 '17 at 06:58
  • thanks for updating the code. i want to generate links for all the directory , subdirectory and files.using this code im only able to print files. something like this favorite 29 Please give me a solution for listing all the folders,subfolders,files in a directory using php.My folder structure is like this Main Dir Dir1 SubDir1 File1 File2 SubDir2 File3 File4 Dir2 SubDir3 File5 File6 SubDir4 File7 File8 – Shesha Chandrika May 03 '17 at 08:30
0

use scandir to get all the files and all the directories in one directory, then use is_dir to make them apart.

<?php
$fileAndDir = scandir('/home/me');
if($fileAndDir !== FALSE)
{
    foreach($fileAndDir as $v)
    {
        if(is_dir($v))
            $dirs[] = $v;
        else
            $files[] = $v;
    }
}
print_r($files);
print_r($dirs);

For all subdirs refer to this post

Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
0

you can do this by having index.php for each directory .. all having this code:

INDEX.PHP

<?php

$currentDir = dirname(__FILE__);
$subDir = scandir($currentDir);

$linkList = '<ul>';
foreach($subDir as $name)
{
$link = '<li>';
$myDirLink = '<a href="' . $name . '/index.php">' . $name . '</a>';
$myFileLink = '<a href="' . $name . '">' . $name . '</a>';
$link .= is_dir($name) ? $myDirLink : $myFileLink;
$link .= '</li>';
$linkList .= $link;
}
$linkList .= '</ul>';
echo $linkList;
?>
Demonyowh
  • 1,673
  • 1
  • 9
  • 14