如何包含需要绝对路径的 PHP 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:08:26  来源:igfitidea点击:

How to include PHP files that require an absolute path?

php

提问by Xenph Yan

I have a directory structure like the following;

我有一个如下所示的目录结构;

script.php

inc/include1.php
inc/include2.php

objects/object1.php
objects/object2.php

soap/soap.php

脚本文件

inc/include1.php
inc/include2.php

对象
/object1.php 对象/object2.php

肥皂/肥皂.php

Now, I use those objects in both script.phpand /soap/soap.php, I could move them, but I want the directory structure like that for a specific reason. When executing script.phpthe include path is inc/include.phpand when executing /soap/soap.phpit's ../inc, absolute paths work, /mnt/webdev/[project name]/inc/include1.php...But it's an ugly solution if I ever want to move the directory to a different location.

现在,我在script.php和中都使用了这些对象/soap/soap.php,我可以移动它们,但是出于特定原因,我想要这样的目录结构。当执行script.php包含路径 isinc/include.php和执行/soap/soap.php它时../inc,绝对路径有效,/mnt/webdev/[project name]/inc/include1.php...但如果我想将目录移动到不同的位置,这是一个丑陋的解决方案。

So is there a way to use relative paths, or a way to programmatically generate the "/mnt/webdev/[project name]/"?

那么有没有一种使用相对路径的方法,或者一种以编程方式生成"/mnt/webdev/[project name]/"?

回答by Peter Coulton

This should work

这应该工作

$root = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$root/inc/include1.php";


Edit:added imporvement by aussieviking

编辑:通过aussieviking添加改进

回答by Kevin

You can use relative paths. Try __FILE__. This is a PHP constant which always returns the path/filename of the script it is in. So, in soap.php, you could do:

您可以使用相对路径。试试__FILE__。这是一个 PHP 常量,它始终返回它所在脚本的路径/文件名。因此,在 中soap.php,您可以执行以下操作:

include dirname(__FILE__).'/../inc/include.php';

The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances. (source)

文件的完整路径和文件名。如果在包含中使用,则返回包含文件的名称。自 PHP 4.0.2 起,__FILE__始终包含已解析符号链接的绝对路径,而在旧版本中,它在某些情况下包含相对路径。 (来源)

Another solution would be to set an include pathin your httpd.conf or an .htaccess file.

另一种解决方案是在 httpd.conf 或 .htaccess 文件中设置包含路径

回答by Christian Hagelid

have a look at http://au.php.net/reserved.variables

看看http://au.php.net/reserved.variables

I think the variable you are looking for is: $_SERVER["DOCUMENT_ROOT"]

我认为您正在寻找的变量是: $_SERVER["DOCUMENT_ROOT"]

回答by Sam McAfee

Another way to handle this that removes any need for includes at all is to use the autoloadfeature. Including everything your script needs "Just in Case" can impede performance. If your includes are all class or interface definitions, and you want to load them only when needed, you can overload the __autoload()function with your own code to find the appropriate class file and load it only when it's called. Here is the example from the manual:

另一种完全不需要包含的处理方法是使用自动加载功能。包括您的脚本所需的一切“以防万一”可能会影响性能。如果包含的都是类或接口定义,并且只想在需要时加载它们,则可以__autoload()使用自己的代码重载该函数以找到合适的类文件并仅在调用时加载它。这是手册中的示例:

function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 

As long as you set your include_path variables accordingly, you never need to include a class file again.

只要您相应地设置了 include_path 变量,就不需要再次包含类文件。

回答by Ryan Fox

You could define a constant with the path to the root directory of your project, and then put that at the beginning of the path.

您可以使用指向项目根目录的路径定义一个常量,然后将其放在路径的开头。

回答by Thane Gill

I found this to work very well!

我发现这很好用!

function findRoot() { 
    return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}

Use:

用:

<?php

function findRoot() {
    return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}

include(findRoot() . 'Post.php');
$posts = getPosts(findRoot() . 'posts_content');

include(findRoot() . 'includes/head.php');

for ($i=(sizeof($posts)-1); 0 <= $i; $i--) {
    $posts[$i]->displayArticle();
}

include(findRoot() . 'includes/footer.php');

?>

回答by Darryl Hein

Another option, related to Kevin's, is use __FILE__, but instead replace the php file name from within it:

与 Kevin 相关的另一个选项是 use __FILE__,而是替换其中的 php 文件名:

<?php

$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);
require_once($docRoot . '/lib/include.php');

?>

I've been using this for a while. The only problem is sometimes you don't have $_SERVER['SCRIPT_NAME'], but sometimes there is another variable similar.

我已经使用了一段时间了。唯一的问题是有时您没有$_SERVER['SCRIPT_NAME'],但有时还有另一个类似的变量。

回答by Polsonby

I think the best way is to put your includes in your PHP include path. There are various ways to do this depending on your setup.

我认为最好的方法是将您的包含放在您的 PHP 包含路径中。根据您的设置,有多种方法可以做到这一点。

Then you can simply refer to

然后你可以简单地参考

require_once 'inc1.php';

from inside any file regardless of where it is whether in your includes or in your web accessible files, or any level of nested subdirectories.

从任何文件内部,无论它是在您的包含文件中还是在您的 Web 可访问文件中,或者任何级别的嵌套子目录中。

This allows you to have your include files outside the web server root, which is a best practice.

这允许您将包含文件放在 Web 服务器根目录之外,这是最佳做法。

e.g.

例如

site directory
    html (web root)
        your web-accessible files
    includes
        your include files

Also, check out __autoload for lazy loading of class files

另外,请查看 __autoload 以延迟加载类文件

http://www.google.com/search?q=setting+php+include+path

http://www.google.com/search?q=setting+php+include+path

http://www.google.com/search?q=__autoload

http://www.google.com/search?q=__autoload

回答by Polsonby

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");

I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.

我使用这行代码。它返回到站点树的“顶部”,然后转到所需的文件。

For example, let's say i have this file tree:

例如,假设我有这个文件树:

domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php

domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php

I can include the functions.php file from wherever i am, just by copy pasting

我可以从任何地方包含functions.php文件,只需复制粘贴

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");

If you need to use this code many times, you may create a function that returns the str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named path_back):

如果您需要多次使用此代码,您可以创建一个返回str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))零件的函数。然后只需将此函数插入​​您包含的第一个文件中。我有一个“initialize.php”文件,它包含在每个 php 页面的最顶部,其中包含此函数。下次我必须包含文件时,我实际上只是使用函数(名为path_back):

require(path_back()."/_resources/another_php_file.php");

回答by yuvraj

If you are going to include specific path in most of the files in your application, create a Global variable to your root folder.

如果要在应用程序的大多数文件中包含特定路径,请为根文件夹创建一个全局变量。

define("APPLICATION_PATH", realpath(dirname(__FILE__) . '/../app'));
or 
define("APPLICATION_PATH", realpath(DIR(__FILE__) . '/../app'));

Now this Global variable "APPLICATION_PATH" can be used to include all the files instead of calling realpath() everytime you include a new file.

现在这个全局变量“ APPLICATION_PATH”可用于包含所有文件,而不是每次包含新文件时调用 realpath() 。

EX:

前任:

include(APPLICATION_PATH ."/config/config.ini";

Hope it helps ;-)

希望能帮助到你 ;-)