如何在php中包含一个文件,并仍然尊重该包含文件的相对链接

时间:2011-11-14 08:52:21

标签: php include-path

我正在尝试使用PHP,并且想知道如何做这样的事情

if (site is wordpress)
    include wordpress index.php;

在wordpress文件中有一行

require('./wp-blog-header.php');

那不会工作,因为它会抛出我找不到文件的错误,但是如果我把它改成这个就行了

require('wp-blog-header.php');

然后我没有遇到问题并且页面加载(因为wp-blog-header.php加载了一些其他相对于wp-blog-header.php的文件,所以那些不会包含或加载)。

有没有办法诱骗PHP保持并尊重相关文件?

编辑:包含我的代码以更好地解决我的问题

if ($app['framework']['type'] && $app['cms']['type']) {    
    echo "Only a Framework or CMS can be loaded at a time...";    
} else {    
    if (is_file("./app/" . $cfg['application']['name'] . "/index.php")) {
        require_once "./app/" . $cfg['application']['name'] . "/index.php";
    } else {    
        if ($app['framework']['type']) {            
            echo "framework";
            //require_once "./app/" . $cfg['application']['name'] . "/" . $app['framework']['type'] . "/index.php";         
        } else if ($app['cms']['type']) {               
            if ($admin) {
                require_once "./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/wp-admin/index.php";
            } else {                        
                $old_working_dir = getcwd();   // Remember where we are now.
                chdir("./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/");            // 'Go into' the Wordpress directory.
                //include("index.php");          // Include the index.php file (no need for 'wordpress/')
                chdir($old_working_dir); 
                require_once "index.php";
            }
        } else {    
            echo "There is no index in your project directory, if your going to use a Framework or CMS please choose one from the following, thank you (list of cms's and frameworks)";
        }
    }    
    exit;
}

3 个答案:

答案 0 :(得分:1)

您可以使用函数getcwd()获取当前工作目录,并使用chdir()进行设置。在你的情况下,它看起来像这样:

$old_working_dir = getcwd();   // Remember where we are now.
chdir("wordpress");            // 'Go into' the Wordpress directory.
include("index.php");          // Include the index.php file (no need for 'wordpress/')
chdir($old_working_dir);       // Go back to the previous directory.

或者:

chdir("wordpress");
include("index.php");
chdir("../");                  // Go back up one level.

答案 1 :(得分:0)

您最好定义一个包含应用程序路径的常量,并将其添加到您执行的每个包含中:

define("APP_PATH", "/var/www/app/");

...

include(APP_PATH . 'foo/bar.php');

答案 2 :(得分:0)

你看过PHP的魔法常量__DIR__吗?

  

文件的目录。如果在include中使用,则返回包含文件的目录。这相当于dirname( FILE )。除非它是根目录,否则此目录名称没有尾部斜杠。 (在PHP 5.3.0中添加。)

如果您使用的是旧版本的PHP,则可以使用dirname(__FILE__)

这是一个小用法示例:

/** 
 * file hierarchy
 * ./index.php
 * ./foo/bar.php
 * ./foo/baz.php
 */

// ./foo/bar.php
include __DIR__.'baz.php';

// ./index.php
include __DIR__.'/foo/bar.php';

您现在可以包含index.php,理论上这些内容仍应有效。与其他答案相比,这也是一种不太苛刻的解决方案。