在导航栏中使用时,相对路径会发生变化

时间:2018-01-23 11:30:06

标签: php include absolute-path

我在我网站的导航栏中使用PHP include()函数。此导航栏又包含在标题中,该标题包含在网站的每个页面上。问题是当我从一个页面移动到另一个页面时,数据库文件的相对位置会发生变化。我不知道如何包含托管网站的绝对路径。 我试着使用这段代码:

$path = $_SERVER['http://mywebsite/'];
$path .= "databaseconnection.php";
include_once($path);

但它不起作用。这段代码也不起作用:

$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "databaseconnection.php";
include_once($path);

请帮帮我。在此先感谢。

1 个答案:

答案 0 :(得分:1)

我将使用webroot的绝对路径定义一个常量。

的config.php:

/* in this constant, the absolute path to the current file 
   (which is placed in the webroot) will be saved */
define('WEBROOT_PATH', realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR);

/subpage/subpage.php

/* you know where the current page is, so you know the relative 
   path to the webroot and can include any file from there */
include_once("../config.php");
/* now you have the constant WEBROOT_PATH included */

...
/* on every page you have your navigation */
include ("../nav/navigation.php");

/nav/navigation.php:

/* the constant WEBROOT_PATH is also accessible here, because you
   incldued it in the parent page, so use it to find your database file- */
$path = WEBROOT_PATH."databaseconnection.php";
include_once($path);