简体   繁体   中英

A href links in PHP include file are not relative to the root

I have a PHP file I am using as the template header for each page of my website. But the links in the PHP template header file are not relative to the root and don't auto update when I create a new page on a deeper subfolder of the root folder.

eg

home/index.php with <?php include("header.php") ?>

home/2ndfolder/index.php with <?php include("../header.php") ?>

home/2ndfolder/3rdfolder/index.php with <?php include("../../header.php") ?>

Each index file listens to the same header.php. And the links inside the header.php have:

eg <a href="../folder_x/">

Each index.php file displays the header.php in the browser but the links are different for each index.php. They are either too many folders back or not enough.

So instead of the links being in relation to the position of the header.php, they are in relation to the current index.php I am previewing in the browser.

I'm using Coda2 which could be the problem, I'm not sure.

I wrote a function for my project that you can use. There might be a more efficient way but it works. What I do is add this getRoot() function in front of all files that I am referencing.

 /**
 * 
 * Return the root of the current page so we can call any page from any folder
 * 
 */
function getRoot(){
    $root = ROOT_DIR;
    $root = str_replace("\\", "/", $root);
    $pageroot = getcwd() ."/";
    $pageroot = str_replace("\\", "/", $pageroot);
    $root = str_replace($root."/", '' , $pageroot);
    $root = preg_replace("#(/.*?).*?(/)#", '/../', "/".$root);
    $root = substr($root, 1);
    return $root;
}

And then set this line on a page that is in your root folder. **Must be defined in your root folder.

define('ROOT_DIR', __DIR__);

Finally you can call the function like this

$file = getRoot()."path/to/file";

Basically the function will add the correct ammount of ../'s to set you back to the root folder. Then you can universally set any variable based off that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM