问题
I'm learning php but am up against a wall right now with a referencing issue. I've searched a lot but I can't find any posts with my exact structural problem. Hoping to master this hurdle so I can move toward the next...
My basic file structure something like:
domain.com/
home.php
images/
global/
nav/
nav-img.jpg
includes/
menu.php
fruit/
apples/
red/
gala/
gala.php
I want to create a global path establishing my web root directory that I can reference on the fly in each page wherever it resides. BUT other posts on this general topic give [10] different functions I can use. I just want [1]. Also, I don't know where to put [for example] define(ROOT), or how to call it from an individual page.
Will define(ROOT) work for my situation?
Knowing that all pages use [menu.php], my obstacle:
From gala/gala.php - when I click on [home], it looks for:
/fruit/apples/red/gala/home.php [does not exist, of course!]
Also, trying to AVOID these [2] things if possible:
I. Using html file references in gala.php like this: ../../../../includes/menu.php
to find the correct global include.
II. And avoid using link references in menu.php like this: /images/global/nav/nav-img.jpg
Any feedback would be appreciated [+] or [-]. Thanks a lot.
回答1:
Ok, here's what I did that seemed the best:
For I. and II. to avoid using so many ../../../../ in all the src="" and href="" I just settled and used site-relative file references with leading slashes, such as "/includes/menu.php" which would get me to the site root, building the file's location from there.
For the global file reference, BOTH of these worked:
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/";
?>
// in `<head>` section
And using <?php include ('menu.php'); ?>
OR THIS ONE WORKED TOO:
<?php
define('ROOT',$_SERVER['DOCUMENT_ROOT']);
define('INCLUDES',ROOT.'/includes/');
?>
// in `<head>` section
And using <?php include (INCLUDES.'menu.php'); ?>
in a file at another level.
来源:https://stackoverflow.com/questions/15399758/broken-links-resulting-from-php-include-references