How to get the relative directory no matter from where it#39;s included in PHP?(无论从 PHP 中的哪个位置获取相对目录?)
问题描述
如果是Path_To_DocumentRoot/a/b/c.php
,应该总是/a/b
.
我用这个:
dirname($_SERVER["PHP_SELF"])
但是当它被另一个目录中的另一个文件包含时它将不起作用.
But it won't work when it's included by another file in a different directory.
编辑
我需要一个文档根目录的相对路径.它在网络应用程序中使用.
I need a relative path to document root .It's used in web application.
我发现还有另一个问题有同样的问题,但还没有被接受的答案.
I find there is another question with the same problem,but no accepted answer yet.
PHP - 将文件系统路径转换为 URL
推荐答案
您是否有权访问 $_SERVER['SCRIPT_NAME']
?如果这样做,请执行以下操作:
Do you have access to $_SERVER['SCRIPT_NAME']
? If you do, doing:
dirname($_SERVER['SCRIPT_NAME']);
应该可以.否则这样做:
Should work. Otherwise do this:
在 PHP <5.3:
substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));
或 PHP >= 5.3:
substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
<小时>
您可能需要将 realpath()
和 str_replace()
所有 转换为
/
以使其完全便携,像这样:
You might need to realpath()
and str_replace()
all to
/
to make it fully portable, like this:
substr(str_replace('\', '/', realpath(dirname(__FILE__))), strlen(str_replace('\', '/', realpath($_SERVER['DOCUMENT_ROOT']))));
这篇关于无论从 PHP 中的哪个位置获取相对目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无论从 PHP 中的哪个位置获取相对目录?


基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01