PHP - 相对路径“需要”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13898894/
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
PHP - Relative paths "require"
提问by Rafay
My directory structure looks like this:
我的目录结构如下所示:
blog -> admin -> index.php
blog.php
db.php
functions.php
I have been trying to include(require, really) blog.phpin the admin/index.php, but facing lots of errors. I'm following a PHP course, and the instructor does the same thing successfully.
我一直在努力include(require真的)blog.php中admin/index.php,但面对大量的错误。我正在学习 PHP 课程,并且讲师成功地做了同样的事情。
admin/index.php:
管理员/index.php:
require "../blog.php";
which, in turn, requires two more files in its directory.
反过来,它的目录中还需要两个文件。
require "db.php";
require "functions.php";
回答by Sam Dufel
If you find that relative include paths aren't working as expected, a quick fix is to prepend __DIR__to the front of the path you're trying to include.
如果您发现相对包含路径没有按预期工作,快速解决方法是__DIR__在您尝试包含的路径的前面添加前缀。
require __DIR__ . "/../blog.php";
It's reasonably clean, and you don't need to modify the include path or working directory.
它相当干净,您不需要修改包含路径或工作目录。
回答by Andy Lester
You need to set the include_pathin your php.ini.
您需要include_path在 php.ini 中设置。
If you want to set it at run-time, use set_include_path().
如果要在运行时设置它,请使用set_include_path().
回答by Yogesh Suthar
If you are including this files db.php and functions.phpin index.phpthen you have to write this code
如果要包含此文件db.php and functions.php,index.php则必须编写此代码
require "../db.php";
require "../functions.php";
OR if you are including this files in blog.phpthen write this code
或者,如果您要包含此文件,blog.php则编写此代码
require "db.php";
require "functions.php";
回答by Niet the Dark Absol
I like to start my files with chdir($_SERVER['DOCUMENT_ROOT']). This allows me to get a nice and logical base path for all my includes.
我喜欢用chdir($_SERVER['DOCUMENT_ROOT']). 这使我能够为我的所有包含获得一个很好且合乎逻辑的基本路径。

