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;
}
- php概述
- php教程
- php环境搭建
- PHP书写格式
- php变量
- php常量
- PHP注释
- php数组
- php字符串 string
- PHP整型 integer
- PHP浮点型 float
- php布尔型
- php数据类型之数组
- php数据类型之对象
- php数据类型之null
- php数据类型之间的转换
- php运算符
- php表达式
- PHP循环控制
- PHP流程控制
- php函数
- php全局变量
- PHP魔术变量
- php命名空间
- php 日期
- PHP包含文件
- php文件
- PHP 文件上传
- php Cookies
- php Sessions
- php email
- php安全email
- php错误处理
- PHP异常处理
- php过滤器
- PHP 高级过滤器
- php json
- php 表单
- PHP MySQL 简介
- PHP 连接 MySQL
- php创建数据库
- php 创建表
- php mysq 插入数据
- PHP MySQL 插入多条数据
- PHP MySQL 预处理语句
- php mysql 读取数据
- php mysql where
- PHP MySQL Order By
- PHP MySQL Update
- PHP MySQL Delete
- php ODBC