第一种方法:get_included_files
正确的解决方案是使用该get_included_files函数:
list($scriptPath) = get_included_files();
这将为您提供初始脚本的绝对路径:
当前工作目录与初始脚本的目录不同
该脚本使用CLI执行,作为相对路径
这是两个测试脚本;主脚本和包含文件:
# C:UsersRedactedDesktopmain.PHP
include __DIR__ . DIRECTORY_SEParaTOR . 'include.PHP';
echoScriptPath();
# C:UsersRedactedDesktopinclude.PHP
function echoScriptPath() {
list($scriptPath) = get_included_files();
echo 'The script being executed is ' . $scriptPath;
}
结果;注意当前目录:
C:>PHP C:UsersRedactedDesktopmain.PHP
The script being executed is C:UsersRedactedDesktopmain.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 script/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(basename($file_path),'',$file_path);
}
} else {
$file_path = null;
}
return $file_path;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。