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 中的哪个位置获取相对目录?
基础教程推荐
- 将变量从树枝传递给 js 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- php中的PDF导出 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
