假设我有一个做重要事情的PHP文件。
doAllTheThings.php:
<?php
include '../importantThing1.php';
include '../importantThing2.php';
include '../importantThing3.php';
//lots more complicated code below
我们还假设我在Web浏览器中输入地址,这花了半分钟,但是所有事情都完成了,众所周知,太好了,让我们不要搞乱它。(有很多合理的理由不去使用它。也许我没有写过,也不了解它。也许我没有访问它的权限。也许这是一个紧急补丁,并且没有时间更新和测试每个包含路径。)
现在假设我希望用户能够做一些可以导致代码运行的事情。
customerInterface.php:
<?php
//lots more complicated code above
if(doTheThings){
include '../../things/important/doAllTheThings.php';
}
它可以运行,但是现在相对路径不起作用。ImportantThing链接已断开。没有重要的事情完成。
如何执行“ doAllTheThings.php”,使其行为与直接在浏览器地址栏中键入地址一样?(无需更改目录结构,文件位置或“ doAllTheThings.php”)
假设没有正在运行的客户端代码,doAllTheThings.php
并且您知道的路径doAllTheThings.php
。
主要问题是如何include
解析嵌套include
文件中的路径。
如果在中找不到该文件
include_path
,include
则最终将在失败之前检入调用脚本的自身目录和当前工作目录。[原文]
在这种情况下,调用脚本为customInterface.php
。
作为在include
做出决议从执行的脚本文件的当前工作目录的相对路径,最简单的方法来规避这一问题并作出调用脚本的行为,如果你执行的doAllTheThings.php
直接,你可以使用chdir
,以改变当前的工作目录。
<?php
//...
if (true) {
//check to make sure doAllTheThings.php actually exists and retrieve the absolute path
if (!$doAllThings = realpath('../../things/important/doAllTheThings.php')) {
throw new \RuntimeException('Unable to find do all things');
}
//change working directory to the same as doAllTheThings.php
chdir(dirname($doAllThings));
//include doAllTheThings from the new current working directory
include $doAllThings;
//change the working directory back to this file's directory
chdir(__DIR__);
}
//...
?>
__DIR__
或dirname(__FILE__)
但是,如果可能的话,我强烈建议使用绝对路径,方法是包括根路径,__DIR__
或者dirname(__FILE__)
在任何相对include
路径之后附加PHP或在PHP <5.3中。这将消除使用chdir()
作为变通办法的需要,并允许PHP解析要包含的正确路径,同时还允许整个应用程序在从其执行脚本的任何系统上运行。
<?php
include __DIR__ . '/../importantThing1.php';
include __DIR__ . '/../importantThing2.php';
include __DIR__ . '/../importantThing3.php';
另一种更复杂的方法是使用来指定包含文件目录set_include_path()
。但是,如果您不知道嵌套的包含脚本所在的目录,则需要您解析包含文件以进行检查。因此,尽管可行,但我不推荐这种方法。
<?php
if ($doAllThings = realpath('../../things/important/doAllTheThings.php') {
//retrieve the directory names of the scripts to be included
$basePath = dirname($doAllThings);
$subPath = dirname($basePath);
//add the directories to the include path
$include_path = set_include_path(get_include_path() . PATH_SEPARATOR . $basePath . PATH_SEPARATOR . $subPath);
include $doAllThings;
//restore the include path
set_include_path($include_path);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句