Broken links resulting from php include references

最后都变了- 提交于 2020-01-06 18:06:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!