php-include(无法获得正确的路径)



我有一个文件位于:

/Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/sidebar-left-big.php

我在子目录中有另一个文件:

/Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/template_directorypress/_gallerypage.php

在_gallerypage.php中,我的php包括:

<?php include('../sidebar-left-big.php'); //left sidebar, category navigation and ads ?>

我得到的错误:

Warning: include(../sidebar-left-big.php) [function.include]: failed to open stream: No such file or directory in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/template_directorypress/_gallerypage.php on line 9
Warning: include() [function.include]: Failed opening '../sidebar-left-big.php' for inclusion (include_path='.:') in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/template_directorypress/_gallerypage.php on line 9

在我看来,我做的每件事都是对的。

我想可能问题是_gallerypage.php是通过include加载到另一个文件中的,所以../相对于此会导致错误。但error并没有说明它认为sidebar-left-big.php的路径在哪里。

使用include dirname(__FILE__).'/../sidebar-left-big.php';

,你是对的。

当包含来自另一个文件的_gallerypage.php时,它确实采用相对于自身的路径。所以,你应该解决这个问题。

最好的办法可能是避免这种困难。有很多方法可以做到这一点。比如,一种方法是在一个常量中定义一个全局根,并根据它包括所有的东西

例如:

define("BASE" , "/wordpress"); //Define a base directory
//now whenever you are including and requirng files, include them on the basis of BASE
require(BASE."/admin/.../some.php");

使用以下代码段并将其保存为php应用程序根目录中的文件(例如config.php)。然后,您可以继续在所有其他PHP文件中引用该文件,以使用变量BASE_PATH和TOP_LEVEL_DIR

<?php
/**
 * @def (string) DS - Directory separator.
 */
define("DS","/",true);
/**
 * @def (resource) BASE_PATH - get a base path.
 */
define('BASE_PATH',realpath(dirname(__FILE__)).DS,true);
define('TOP_LEVEL_DIR', public_base_directory());
?>
<?php
function public_base_directory()
{
    //get public directory structure eg "/top/second/third"
    $public_directory = dirname($_SERVER['PHP_SELF']);
    //place each directory into array
    $directory_array = explode('/', $public_directory);
    //get highest or top level in array of directory strings
    $public_base = max($directory_array);
    return $public_base;
}
?>

相关内容

  • 没有找到相关文章

最新更新