如何在 .htaccess 中将路径附加到 PHP 的 include_path
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1135206/
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
How to append a path to PHP's include_path in .htaccess
提问by zildjohn01
Currently on my site I'm using statements like:
目前在我的网站上,我正在使用以下语句:
include 'head.php';
include '../head.php';
include '../../head.php';
depending on how many nested folders deep I am. I'm sure there is a better way to do this.
取决于我有多少嵌套文件夹。我相信有更好的方法来做到这一点。
I'm convinced .htaccessis the solution, but I'm not sure how to go about implementing it. If I insert:
我确信这.htaccess是解决方案,但我不确定如何实施它。如果我插入:
php_value include_path "public/html/root"
... I lose the rest of my paths (/usr/lib/php, etc). I naively tried:
...我失去了我的其余路径(/usr/lib/php等)。我天真地尝试:
php_value include_path $include_path . "(path)"
but of course this didn't work. How could I prepend or append a single path to this list with .htaccess?
但当然这没有用。我如何在此列表中添加或附加单个路径.htaccess?
采纳答案by Otterfan
If you can't edit the php.inifile itself, you could add
如果您无法编辑php.ini文件本身,则可以添加
set_include_path(get_include_path() . PATH_SEPARATOR . $path_to_add);
before your includestatements.
在你的include陈述之前。
However if you find yourself having includeor requiretroubles, it is probably a code smell. The best solution would be a good object-oriented design with a good __autoloadfunction.
但是,如果您发现自己遇到include或require遇到麻烦,则可能是代码异味。最好的解决方案是具有良好__autoload功能的良好面向对象设计。
回答by nalply
Create in the sub-sub-directories a file .htaccesswith the contents
在子子目录中创建一个.htaccess包含内容的文件
php_value include_path '../../includes'
or whatever include_pathis right for that directory.
或include_path适合该目录的任何内容。
Advantages:
好处:
- No ugly hack with multiple includes with different depth. Just
include 'head.php'. - No dependency on editing
php.ini. - No need to use
set_include_path()before including. - No dependency on including constants like
include INCLUDE_PATH . 'head.php'.
- 没有具有不同深度的多个包含的丑陋黑客。只是
include 'head.php'。 - 不依赖于编辑
php.ini。 set_include_path()包含之前无需使用。- 不依赖于包含像
include INCLUDE_PATH . 'head.php'.
Price to pay:
支付价格:
You litter your sub-sub-directories each with a file .htaccess.
您将每个子目录都放在一个文件中.htaccess。

