Path of current PHP script relative to document root

匆匆过客 提交于 2019-12-05 02:50:40

What I've done in the past is to use a setup like this:

define('DIR_BASE',     dirname( __FILE__ ).'/'); 
define('DIR_SYSTEM',   DIR_BASE.'app/');
etc.

This would be placed in a file root of your project, which will give you access to other areas of your file structure relative to the root.

For your case, it would look like this:

define('DIR_BASE',     dirname( __FILE__ ).'/');
define('DIR_CSS',      DIR_BASE.'css/');
define('DIR_PHP',      DIR_BASE.'php/');
define('DIR_CONTENT'   DIR_BASE.'content/');

This would go in getpath.php in your root, and would give you the ability to reference any file or directory regardless of where it is placed in the directory structure (be sure to include it wherever you'll be using them). You wouldn't need to change your directory structure or anything like that, and you don't have to worry about any vulnerabilities with something like this, since it's internal.

Edit I keep coming back to the structure of the system. Is this a multi-site system that uses the same CSS through out? If not, then what is the justification for having the directory structure laid out like this? Can you give just a little more detail please?

Looks like the best way to do this is removing $_SERVER['DOCUMENT_ROOT'] from __DIR__, as I mentioned in the original question.

define('PROJECT_DIR', preg_replace('/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/', '', __DIR__));

I think I'm just going to do it like that.

I have a config/ folder in my project root with a file called main.php, I use this:

$root = $_SERVER['DOCUMENT_ROOT'];
$dir = dirname(__DIR__);
$root = str_replace("\\","/",$root);
$dir = str_replace("\\","/",$dir);
$web_dir = str_replace($root,'',$dir);
if ($web_dir!=='') { $web_dir = '/'.$web_dir; }
define('DIR',$web_dir);

this removes the doc root from the full directory path of my config file, thus giving me the actual path relative to web root. If your config file was in the root of your project you would remove this line:

$dir = dirname(__DIR__);

relative URL, or where your script located relative to document root

preg_replace('/[\\\\\\/]+/', '/', '/' . substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT'])) . '/' )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!