获取初始运行脚本的绝对路径 [英] Get absolute path of initially run script

查看:83
本文介绍了获取初始运行脚本的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了上下搜索,并获得了许多不同的解决方案和包含信息的变量以获取绝对路径.但是它们似乎在某些条件下工作,而不是在其他条件下工作.有没有一种灵丹妙药的方式来获取PHP中已执行脚本的绝对路径?对我来说,该脚本将从命令行运行,但是,如果在Apache等内部运行,则解决方案也应能正常运行.

说明:最初执行的脚本,不一定是解决方案的编码文件.

解决方案

正确的解决方案是使用 解决方案

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

这篇关于获取初始运行脚本的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆