PHP获取当前脚本的绝对路径

时间:2017-07-27
本文章向大家介绍php获取当前脚本的绝对路径的几种方法,需要的朋友可以参考一下。

第一种方法:get_included_files

正确的解决方案是使用该get_included_files函数

list($scriptPath) = get_included_files();

这将为您提供初始脚本的绝对路径:

  • 此功能放在包含的文件中
  • 当前工作目录与初始脚本的目录不同
  • 该脚本使用CLI执行,作为相对路径

这是两个测试脚本; 主脚本和包含文件:

# C:\Users\Redacted\Desktop\main.php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();

# C:\Users\Redacted\Desktop\include.php
function echoScriptPath() {
    list($scriptPath) = get_included_files();
    echo 'The script being executed is ' . $scriptPath;
}

结果; 注意当前目录:

C:\>php C:\Users\Redacted\Desktop\main.php
The script 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 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;
}