【问题标题】:PHP - Redirecting and including files from different directoriesPHP - 重定向和包含来自不同目录的文件
【发布时间】:2014-01-13 00:25:21
【问题描述】:
假设我有这个给定的目录
public_html
index.php
现在假设我想在 page1.php 中包含 page2.php
我这样做:
包括“/home/page2.php”;
但是不行,/应该是根目录(public_html)。
或者我想从 reg.php 重定向到 index.php
“/index.php”不起作用。
注意:这一切都在托管服务器上。
【问题讨论】:
标签:
php
include
directory
web-hosting
include-path
【解决方案1】:
/ 不是站点根目录,它是您的操作系统文件系统的根目录。
您可以像这样使用相对路径修饰符:../../yourincludefile.php 在文件系统中向上导航
或者您可以使用$_SERVER['DOCUMENT_ROOT'] 从操作系统调用完整路径。 DOCUMENT_ROOT 将为您提供更一致的结果,并且无论您在目录层次结构中的哪个位置工作,都可以包含相同的文件。
例如,如果您有includes/functions.php,您可以在任何地方、任何脚本上使用它,并且它始终包含正确的文件路径:
include_once($_SERVER[DOCUMENT_ROOT] . "/includes/functions.php");
或使用字符串内的引用:
include_once("$_SERVER[DOCUMENT_ROOT]/includes/functions.php");
【解决方案2】:
您应该能够使用相对路径,即:
我想在 page1.php 中包含 page2.php 我这样做:
include "../page2.php";
我想从 reg.php 重定向到 index.php
"../../index.php"
或者,如果您在 public_html 中谈论 index.php,
"../../../index.php"
【解决方案3】:
选项 1 - 相对文件:
include("../path/to/file.php");
选项 2 - 根相对
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");