PHP动态包括基于当前文件路径

Adr*_* M. 11 php filenames dynamic include

我想找到一种方法来包含一些基于当前文件路径的文件..例如:

我有"website.com/templates/name1/index.php",这个"index.php应该是一个独特的文件,我将在不同深度的许多不同目录中使用,所以我想让代码通用,所以我不喜欢需要更改此文件中的任何内容..

所以,如果这个"index.php"位于

" website.com /templates/name1/index.php"

它应该包括位于这里的文件:

" website.com/content /templates/name1/content.php"

另一个例子:

" website.com /templates/name2/index.php"

它应该包括位于这里的文件:

" website.com/content /templates/name2/content.php"

另外我想要溢出" 警告:include_once()[function.include-once]:http://在服务器配置中禁用包装器allow_url_include = 0 "错误类型..因为已禁用且不安全..

有没有办法实现这个目标?谢谢!

Ser*_*sov 31

我认为你需要使用__FILE__(它在名称的开头和结尾有两个下划线)和DIRECTORY_SEPARATOR常量来处理基于当前文件路径的文件.

例如:

<?php
  // in this var you will get the absolute file path of the current file
  $current_file_path = dirname(__FILE__);
  // with the next line we will include the 'somefile.php'
  // which based in the upper directory to the current path
  include(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'somefile.php');
Run Code Online (Sandbox Code Playgroud)

使用DIRECTORY_SEPARATOR常量比使用"/"(或"\")符号更安全,因为Windows和*nix目录分隔符是不同的,并且您的解释器将在不同平台上使用适当的值.