【问题标题】:Get full path from filename in php从php中的文件名获取完整路径
【发布时间】:2013-02-17 02:27:38
【问题描述】:

所以我有一个包含 &title=blabla

的 URL

我知道如何提取标题并返回它。但是当我只有文件名时,我一直在寻找文件名的完整路径。

所以我必须拥有一种在所有目录中搜索名为“blabla”的 html 文件的方法,而该文件只有 blabla。找到后必须返回完整路径。

谁有我的解决方案?

<?php

$file = $_GET['title'];

if ($title = '') {
echo "information.html";
} else { 
//here it must search for the filepath and echo it.
echo "$filepath";
}

?>

【问题讨论】:

  • 添加示例...您拥有什么以及您想要什么...
  • One Trick Pony 的解决方案应该可以解决这个问题,只需将 $root 变量设置为包含您的内容页面的文件夹,以避免搜索不必要的文件夹。否则如前所述,它将非常迟钝。

标签: php filenames filepath


【解决方案1】:

您可以使用here提供的解决方案。

它允许您通过目录递归并列出目录和子目录中的所有文件。然后,您可以比较它是否与您要查找的文件匹配。

【讨论】:

    【解决方案2】:
    $root = '/';               // directory from where to start search
    $toSearch = 'file.blah';   // basename of the file you wish to search
    
    $it = new RecursiveDirectoryIterator($root);
    foreach(new RecursiveIteratorIterator($it) as $file){
      if($file->getBasename() === $toSearch){
        printf("Found it! It's %s", $file->getRealPath());
    
        // stop at the first match
        break;
      }
    }
    

    请记住,根据您拥有的文件数量,这可能会非常慢

    【讨论】:

    • 创建一个包含所有路径的 .txt 并仅搜索一行是否包含文件名会更快,如果是则回显该行?
    • 如果该列表被创建一次,是的。我猜你可以在每次$root 目录的修改日期更改时重建列表
    【解决方案3】:

    首先这条线路有问题

    if ($title = '') {
    

    http://www.php.net/manual/en/reserved.variables.files.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多