无论从 PHP 中的哪个位置获取相对目录? [英] How to get the relative directory no matter from where it's included in PHP?

查看:28
本文介绍了无论从 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 中的哪个位置获取相对目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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