Path of current PHP script relative to document root

前端 未结 4 2018
一整个雨季
一整个雨季 2021-02-14 09:08

TL;DR: What alternatives to the last code sample on this page are there when trying to use relative links on pages included with PHP\'s include com

相关标签:
4条回答
  • 2021-02-14 09:28

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

    preg_replace('/[\\\\\\/]+/', '/', '/' . substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT'])) . '/' )
    
    0 讨论(0)
  • 2021-02-14 09:38

    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.

    0 讨论(0)
  • 2021-02-14 09:47

    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__);
    
    0 讨论(0)
  • 2021-02-14 09:50

    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?

    0 讨论(0)
提交回复
热议问题