当使用include(或require)语句时,使用header('Location:$ url')

时间:2016-07-17 14:46:49

标签: php redirect xampp

假设有一个文件树

/[PROJECT_ROOT]/include-caller-1.php
/[PROJECT_ROOT]/subfolder/yet-another-include-caller-2.php
/[PROJECT_ROOT]/subfolder/subfolder2/yet-another-include-caller-3.php
/[PROJECT_ROOT]/subfolder/page-get-included.php
/[PROJECT_ROOT]/subfolder/jump-to-this-page.php

三个'include-caller.php',包含'page-get-included.php',包含正确的'include'语句。

/include-caller-1.php

include("/subfolder/page-get-included.php");

/subfolder/yet-another-include-caller-2.php

include("page-get-included.php");

/subfolder/subfolder2/yet-another-include-caller-3.php

include("../page-get-included.php");

在/subfolder/page-get-included.php中,它会重定向到'jump-to-this-page.php',例如:

header("Location: " . realpath(dirname(__FILE__) . "/jump-to-this-page.php"));

但它不会按预期工作。

此外,[PROJECT_ROOT]htdocs的相对位置是灵活的。它可能是htdocs/project/htdocs/等。

总之,$_SERVER['DOCUMENT_ROOT']和caller.php的位置都不可预测。只有一件事是真的:'page-get-included.php'和'jump-to-this-page.php'就在彼此旁边。

在这种情况下,如何从所有可能的调用者文件中统一重定向到“jump-to-this-page.php”?

1 个答案:

答案 0 :(得分:2)

通过查找page-get-included.php

$path_real = __DIR__;
$path_real_difference = str_replace($path_real, '', $_SERVER['SCRIPT_FILENAME']);
$path_web = str_replace($path_real_difference, '', $_SERVER['SCRIPT_NAME']);

现在,您可以将此路径引用至jump-to-this-page.php,无论其位于何处。

header("Location: $path_web/jump-to-this-page.php");