-1

Need help for a php script / page for generating links to folders. Have a homepage with photos that I upload using Lightroom – each album in a separate folder.

The structure is:

mysite.com  
  |--images  
    |--folder1  
    |--folder2  
    |--folder3  
    .  
    . 

So I would like to end up with a dynamic index.php file that generates links to all the subfolders of “images” instead of the static index.html file I got in the root of mysite.com:

<html>
  <body>
    <a href="mysite.com/images/folder1" target="_blank">folder1</a>
    <a href="mysite.com/images/folder2" target="_blank">folder2</a>
    <a href="mysite.com/images/folder3" target="_blank">folder3</a>
    .
    .
  </body>
</html>

Thanx in advance

3 Answers3

1
<?php
    $files = scandir();
    $dirs = array(); // contains all your images folder
    foreach ($files as $file) {
        if (is_dir($file)) {
           $dirs[] = $file;
        }
    }
?>

use dirs array for dynamically generating links

user2576951
  • 198
  • 1
  • 9
0

Try something like this:

$contents = glob('mysite.com/images/*');
foreach ($contents as content) {
    $path = explode('/', $content);
    $folder = array_pop($path);
    echo '<a href="' . $content . '" target="_blank">' . $folder . '</a>';
}

Or also this:

if ($handle = opendir('mysite.com/images/') {
    while (false !== ($content = readdir($handle))) {
        echo echo '<a href="mysite.com/images/' . $content . '" target="_blank">' . $content . '</a>';
    }
    closedir($handle);
}
searsaw
  • 3,492
  • 24
  • 31
0

Maybe something like this:

$dir = "mysite.com/images/";
$dh = opendir($dir);
while ($f = readdir($dh)) {
  $fullpath = $dir."/".$f;
  if ($f{0} == "." || !is_dir($fullpath)) continue;
  echo "<a href=\"$fullpath\" target=\"_blank\">$f</a>\n";
}
closedir($dh);

When I need everything (i.e., something/*), I prefer readdir() over glob() because of speed and less memory consumption (reading a directory file by file, instead of getting the whole thing in an array).

If I'm not mistaken, glob() does omit .*files and has no need for the $fullpath variable, so if you're after speed, you might want to do some testing.

Community
  • 1
  • 1
Vedran Šego
  • 3,553
  • 3
  • 27
  • 40
  • I gave the glob as an option since it's quick if you're only needing this for something quick and simple. – searsaw Jul 20 '13 at 02:23
  • Thanx for the quick answers. The last one worked “out of the box”. Will study the others more carefully tomorrow – need to hit the sack – its 04:40 in Denmark ;-) – Jonas Hansen Jul 20 '13 at 02:48
  • @searsaw My comment was not aiming towards anyone in particular. As I said, I think `glob()` is something to be considered, although I'd expect `readdir()` to be more appropriate in this case. – Vedran Šego Jul 20 '13 at 09:26