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

查看:84
本文介绍了无论如何从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.

编辑

我需要一个相对路径来记录根目录.它在Web应用程序中使用.

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天全站免登陆