duan1226 2011-01-10 09:02 采纳率: 100%
浏览 56
已采纳

获取当前脚本的绝对路径

I have searched high and low and get a lot of different solutions and variables containing info to get the absolute path. But they seem to work under some conditions and not under others. Is there one silver bullet way to get the absolute path of the executed script in PHP? For me, the script will run from the command line, but, a solution should function just as well if run within Apache etc.

Clarification: The initially executed script, not necessarily the file where the solution is coded.

  • 写回答

15条回答 默认 最新

  • dongyuchen9276 2018-03-01 08:31
    关注

    The correct solution is to use the get_included_files function:

    list($scriptPath) = get_included_files();
    

    This will give you the absolute path of the initial script even if:

    • This function is placed inside an included file
    • The current working directory is different from initial script's directory
    • The script is executed with the CLI, as a relative path

    Here are two test scripts; the main script and an included file:

    # 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;
    }
    

    And the result; notice the current directory:

    C:\>php C:\Users\Redacted\Desktop\main.php
    The script being executed is C:\Users\Redacted\Desktop\main.php
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料