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

时间:2012-07-22 10:01:26

标签: php wordpress include-path

我有一个文件位于:

/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加载到另一个文件中的,所以../相对于那会导致错误。但是错误并没有说出它认为sidebar-left-big.php的路径在哪里。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

,你是对的。

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

最好的办法,可能是避免这种困难。有很多方法可以做到这一点。比如,One会在一个常量中定义一个全局根,并按照它包含所有内容。

例如:

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

答案 2 :(得分:0)

使用以下代码段并将其另存为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;
}
?>
相关问题