php - Dynamically add the same CSS file from different pages at different directory depths -


okay i've been trying figure out while now. have website i'm working on , here structure:

index.php page-x/     index.php     page-x-y/         index.php include/     functions.php css/     main.css 

except add on more sub-folders , index pages. pages @ 3 different levels.

they need have css/main.css, path 1 index page going different.

right use functions.php add css, , have manually enter relative path index page functions.php (ie require_once("../include/functions.php"); or ../../include etc

how can make functions.php can figure out relative path index page included on, css/main.css?

i.e. how define $reldir following code in functions.php:

echo '<link rel="stylesheet" type="text/css" href="' . $reldir . 'css/main.css" />'; 

i manually pass "" or "../" or "../../" every-time function, can avoid that?


edit 3 if define $base = dirname(__dir__); in functions.php, can find root of site , go there absolute path css.

however css doesn't seem link properly, on local machine resulting link looks like: (i can manipulate slashes consistent doesn't help)

"c:\documents , settings\lucas\site/css/main.css" 

(note: using alias on easyphp can connect address http://127.0.0.1:8888/site/ but__dir__ finds actual directory of file.

and on (my universities) server testing on comes with

"/volumes/web/students/myname/sites/mysite/css/main.css" 

the actual url of website looks like:

http://www.school.com/myname/mysite/ 

the css wont link in either situation


edit 2 can define $reldir as:

 str_repeat('../', substr_count($_server['request_uri'], '/'); 

returns 1 of following depending on how deep index is:

"" "../" "../../" 

this lot of processing apparently though. sounds best thing proper testing environments, , use absolute path. i'll that. i'm still bit of newb of stuff.


edit 1: okay people suggesting stick doing manually, had function call this:

<?php require_once("../include/functions.php"); buildhead("music", "../"); //($title, $reldir) ?> 

i have change ../ whatever in both places every page.

easiest way? use absolute paths. if website stays on single fixed path it's easy. if want keep free change structure of site, add configuration parameter -- eg. include config file on top of each php file , define $base parameter there holds absolute path of app base, do:

echo '<link rel="stylesheet" type="text/css" href="'.$base.'/css/main.css" />' 

if $base empty, default root of webserver.

you can processing automatically, using __dir__ magic constant (or __file__ if using php < 5.3 doesn't change - need strip file name get). if include config file @ top of each php file (or use apache auto prepend directive), , config file located in base directory of website, sufficient:

$base = __dir__; 

otherwise, if sits in directory, need go up, known when deploying , not dependent on request.


Comments