如何在.htaccess中附加到PHP的include_path的路径

zil*_*n01 31 php .htaccess include-path

目前在我的网站上我使用的语句如下:

include 'head.php';
include '../head.php';
include '../../head.php';
Run Code Online (Sandbox Code Playgroud)

取决于我有多少嵌套文件夹.我确信有更好的方法可以做到这一点.

我确信这.htaccess是解决方案,但我不确定如何实施它.如果我插入:

php_value include_path "public/html/root"
Run Code Online (Sandbox Code Playgroud)

......我失去了其余的路径(/usr/lib/php等等).我天真地尝试过:

php_value include_path $include_path . "(path)"
Run Code Online (Sandbox Code Playgroud)

但当然这没用.我怎么能在这个列表中添加或附加单个路径.htaccess

nal*_*ply 28

在子子目录中创建.htaccess包含内容的文件

php_value include_path '../../includes'
Run Code Online (Sandbox Code Playgroud)

或者include_path适合该目录的任何内容.

好处:

  1. 没有丑陋的黑客,包含不同深度的多个包含.只是include 'head.php'.
  2. 不依赖于编辑php.ini.
  3. set_include_path()包括之前无需使用.
  4. 不依赖于包含常量include INCLUDE_PATH . 'head.php'.

支付价格:

你把每个子目录都丢弃了一个文件.htaccess.

  • 我喜欢它,并且通过清晰明确的利益和成本来欣赏这篇文章.我不喜欢乱扔垃圾,但我正在做.谢谢!:) (2认同)

Ott*_*fan 23

如果您无法编辑php.ini文件本身,则可以添加

set_include_path(get_include_path() . PATH_SEPARATOR . $path_to_add);
Run Code Online (Sandbox Code Playgroud)

在你的include陈述之前.

但是,如果你发现自己有麻烦includerequire麻烦,那可能就是代码味道.最好的解决方案是良好的面向对象设计,具有良好的__autoload功能.