PHP获取当前脚本的绝对路径
|
第一种方法: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中,它将返回: www / http / html / class / myclass.php;如果您将此代码放在myclass.php中,它将返回: 第三种方法: /** * 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; } (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
