PHP动态包含基于当前文件路径 [英] PHP Dynamic include based on current file path

查看:168
本文介绍了PHP动态包含基于当前文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法来根据当前文件路径包含一些文件。例如:



我有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



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

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



另外我想要超支警告:include_once()[function.include-once]:http: //包装器在服务器配置中被禁用,allow_url_include = 0 这种错误..因为被禁用和不安全。



有没有办法实现这个
谢谢!

解决方案

我想你需要使用 __ FILE __ (它有两个基于当前文件路径处理文件的常量,名称开头和结尾处都有下划线)和 DIRECTORY_SEPARATOR 常量。



例如:

 <?php 
//在此var中,您将获得当前文件的绝对文件路径
$ current_file_path = dirname(__ FILE__);
//与下一行我们将包含'somefile.php'
//它位于上层目录中的当前路径
include(dirname(__ FILE__))DIRECTORY_SEPARATOR。 '.DIRECTORY_SEPARATOR''somefile.php');

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


I want to find a method to include some files based on the current file path.. for example:

I have "website.com/templates/name1/index.php", this "index.php should be a unique file that I will use in many different directories on different depths, so I want to make the code universal so I don't need to change anything inside this file..

So if this "index.php" is located in

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

than it should include the file located here:

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

another example:

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

than it should include the file located here:

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

Also I want to overrun "Warning: include_once() [function.include-once]: http:// wrapper is disabled in the server configuration by allow_url_include=0" kind of error.. because is disabled and unsafe..

Is there a way to achieve this? Thank you!

解决方案

I think you need to use __FILE__ (it has two underscores at the start and at the end of the name) and DIRECTORY_SEPARATOR constants for working with files based on the current file path.

For example:

<?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');

Using DIRECTORY_SEPARATOR constant is more safe than using "/" (or "\") symbols, because Windows and *nix directory separators are different and your interpretator will use proper value on the different platforms.

这篇关于PHP动态包含基于当前文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆