【问题标题】:Relative path changes when used in a navigation bar在导航栏中使用时相对路径会发生变化
【发布时间】:2018-07-02 05:02:59
【问题描述】:

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

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

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

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

请帮助我。提前致谢。

【问题讨论】:

  • 您是否使用 mod-rewrite/htaccess 来缩短您的网址?
  • 不,没什么

标签: php include absolute-path


【解决方案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);

【讨论】:

  • 我可以简单地复制配置文件的代码,还是我需要指定一些文件名或路径
  • 我无法理解如何使用此代码。在哪里指定我的文件名和路径。你能推荐一些资源来帮助我更好地理解这一点吗?
  • 我对上面的代码做了一些cmets希望现在更容易理解。
  • 谢谢,但这仅在我提供如下路径时有效:C:\Users\... 但当我将其提供为 https://...
猜你喜欢
  • 2017-06-22
  • 2023-03-31
  • 2021-09-24
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 2017-04-21
相关资源
最近更新 更多