【问题标题】:php script for generating links to folders用于生成文件夹链接的 php 脚本
【发布时间】:2013-07-19 10:26:46
【问题描述】:

需要帮助生成文件夹链接的 php 脚本/页面。 有一个主页,其中包含我使用 Lightroom 上传的照片 - 每个相册都在一个单独的文件夹中。

结构是:

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

所以我想最终得到一个动态 index.php 文件,该文件生成指向“图像”的所有子文件夹的链接,而不是我在 mysite.com 的根目录中获得的静态 index.html 文件:

<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>

提前感谢

【问题讨论】:

  • 你已经尝试过哪些代码?

标签: php


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

使用 dirs 数组动态生成链接

【讨论】:

    【解决方案2】:

    可能是这样的:

    $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);
    

    当我需要所有东西(即something/*)时,我更喜欢readdir() 而不是glob(),因为speed 和更少的内存消耗(逐个文件读取目录文件,而不是把整个东西放在一个数组中)。

    如果我没记错的话,glob() 确实省略了.*files 并且不需要$fullpath 变量,所以如果您追求速度,您可能需要进行一些测试。

    【讨论】:

    • 我提供了 glob 作为一个选项,因为如果您只是为了快速简单的事情需要它,它会很快。
    • 感谢您的快速解答。最后一个“开箱即用”。明天会更仔细地研究其他人——需要下班——在丹麦 04:40 ;-)
    • @searsaw 我的评论并非针对任何人。正如我所说,我认为 glob() 是值得考虑的事情,尽管我希望 readdir() 在这种情况下更合适。
    【解决方案3】:

    试试这样的:

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

    或者这个:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-28
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多