Path of current PHP script relative to document root

前端 未结 4 2010
一整个雨季
一整个雨季 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: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__);
    

提交回复
热议问题