第一种方法:get_included_files
正确的解决方案是使用该get_included_files函数:
list($ Path) = get_included_files();
这将为您提供初始脚本的绝对路径:
- 此功能放在包含的文件中
- 当前工作目录与初始脚本的目录不同
- 该脚本使用CLI执行,作为相对路径
这是两个测试脚本; 主脚本和包含文件:
# C:\\Users\\Redacted\\Desktop\\main.php
include __DIR__ . DIRECTORY_SEPARATOR . \'include.php\';
echo Path();
# C:\\Users\\Redacted\\Desktop\\include.php
function echo Path() {
list($ Path) = get_included_files();
echo \'The being executed is \' . $ Path;
}
结果; 注意当前目录:
C:\\>php C:\\Users\\Redacted\\Desktop\\main.php
The being executed is C:\\Users\\Redacted\\Desktop\\main.php
第二种方法:
dirname(__FILE__)
给出 您要求路由的当前文件的绝对路由,即服务器目录的路由。
示例文件:
www / http / html / index.php; 如果您将此代码放在index.php中,它将返回:
<?php echo dirname(__FILE__); // this will return: www/http/html/
www / http / html / class / myclass.php; 如果您将此代码放在myclass.php中,它将返回:
<?php echo dirname(__FILE__); // this will return: www/http/html/class/
第三种方法:
/**
* Get the file path/dir from which a /function was initially executed
*
* @param bool $include_filename include/exclude filename in the return string
* @return string
*/
function get_function_origin_path($include_filename = true) {
$bt = debug_backtrace();
array_shift($bt);
if ( array_key_exists(0, $bt) && array_key_exists(\'file\', $bt[0]) ) {
$file_path = $bt[0][\'file\'];
if ( $include_filename === false ) {
$file_path = str_replace( name($file_path), \'\', $file_path);
}
} else {
$file_path = null;
}
return $file_path;
} 继续阅读与本文标签相同的文章
-
绑了银行卡的微信,一定要删除这个记录,不然钱被转了都不知道
2026-05-15栏目: 教程
-
Python基础知识储备,List集合基本操作大盘点
2026-05-15栏目: 教程
-
从五个特点突出表述建设智慧城市必要性
2026-05-15栏目: 教程
-
5G核心网建设是采用SA独立组网还是NSA独立组网
2026-05-15栏目: 教程
-
买了iPhone手机,旧设备上数据怎样迁移,这有3种办法快速解决
2026-05-15栏目: 教程
