【问题标题】:How to use include() properly?如何正确使用 include()?
【发布时间】:2015-01-25 20:10:18
【问题描述】:

这是我的结构目录:

Main directory
  all.php
  file.php
  URL1.txt
  SubDirectory1
     URL2.txt
     file.php

文件 file.php 像这样:

 $filename = glob("URL*");
 echo $filename[0];

文件all.php

<?php
    include('./SubDirectory1/file.php');

?>

问题是当我运行文件 all.php 时,浏览器显示 URL1.txt。为什么它不显示 URL2.txt。如何解决?谢谢!

【问题讨论】:

  • 因为脚本file.php是从all.php的位置执行的,所以在这个文件夹中只有URL1.php被发现!
  • 试试这个glob("SubDirectory1/*");
  • @Indrasinh Bihola,嗨,有什么方法可以自动添加子目录?因为我有很多子目录,所以很难一一更改。

标签: php require


【解决方案1】:

工作目录设置为主脚本位置。尝试输入您要搜索的位置的完整路径:

 $filename = glob(__DIR__ . DIRECTORY_SEPARATOR . 'URL*');

__DIR__ 是当前文件目录(从 PHP 5.3 开始,对于较低的 php 版本使用 dirname(__FILE__))。

http://php.net/manual/en/language.constants.predefined.php

【讨论】:

    【解决方案2】:

    只需将此函数放入file.php。你会得到一个数组,你可以var_dump()

    function glob_recursive($pattern) {
        $files = glob($pattern);
    
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern)));
    
        return $files;
    }
    

    在您的 all.php 文件中,您可以这样做:

    print_r(glob_recursive("URL*"));
    

    您将获得所有具有此模式的文件名!所以你可以使用你的file()函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-02
      • 2013-10-13
      • 2016-10-01
      • 1970-01-01
      • 2021-12-13
      • 2020-11-01
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多