简体   繁体   中英

Relative paths for included PHP files

I have a PHP project with the following directory structure:

ROOT
    - PUBLIC
        - CSS
        - JS
    - LIB
        - CONTROLLER

All the basic PHP pages are located under PUBLIC folder while all the controllers, models etc are located under the LIB or CONTROLLER folder. In some cases, after the controller has finished processing, it will include a file from the PUBLIC folder to display. What I notice is that the included file cannot find the associated CSS or JS files because it is now working with the relative path of /LIB/CONTROLLER .

My question:

  1. Is there some way to set a different relative path for the included file without having to modify every single CSS or JS include lines?

  2. This problem does not occur if I forward the control using header (Location...) but in some instances, I prefer not to do this and just include the page - because I will have to pass heavy objects from the controller to the page using SESSION. Is there some better way to achieve this?

As answered by @Jack T - the solution to this problem is to define the <base> element in the included PHP / HTML page. One thing I learnt is that when defining the element use the full URL including http://

This solved the problem I was facing

Use something like this on all your php files:

if( not defined PATH_TO_ROOT ) define PATH_TO_ROOT = '.'

So, in your links and stuff, always make the urls with this constant, like this:

url = PATH_TO_ROOT.'/public/css/mycss.css';

** Please note this is just a pseudo-code and not actual PHP code.

/use/absolute/paths/everywhere/on/your/site

do/not/use/relative/ones
^ see, no /slash , not good practice.

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