0

I have a php includes file in includes/template.php. In this file, I have included two more files that are present in the same directory,(a header and footer file).

The files in the root directory that include the header and footer files work fine, its just the template.php file that screws up, as it doesn't load the css and javascript files from css/style.css and script/main.js. I've looked online and found people that suggest using $_SERVER['DOCUMENT_ROOT'];, but this doesn't work when I do it like this :

include($_SERVER['DOCUMENT_ROOT'].'/includes/header.php');

include($_SERVER['DOCUMENT_ROOT'].'/includes/footer.php');

Thanks in advance.

Repub619
  • 69
  • 2
  • 9
  • 1
    Your includes already worked, so there is no reason to mess with the path in that place. It is not PHP that is trying to load anything here in the first place - it is the browser. And how it resolves the _relative_ path to your CSS and JS files, depends on what URL the main document was loaded from. A different number of “folders” in the URL path of course changes how relative paths are resolved as well. Easiest solution: Use paths beginning with a slash, `/css/style.css` - that always refers to the “domain root”, no matter what the current URL path is. – 04FS Mar 06 '19 at 15:36
  • @04FS Adding a / did not fix it, in fact, my other pages that are on my root cannot find the css files anymore.My server root is localhost/dir/index.php – Repub619 Mar 06 '19 at 16:09
  • Nevermind, adding `/Webapp/css/style.css` worked. Thanks. – Repub619 Mar 06 '19 at 16:12

1 Answers1

1

If your server root directory matches your website root (e.g. localhost/index.php is your main page) you can just add a leading / to your resources path : /script/main.js.

This is because your specifying a relative path : if you visit localhost/dir/index.php, the path the browser will look localhost/dir/script/main.js.

Putting a leading / will convert the path to an absolute path and thus it will be consistent across your website.

If your server root does not match your website root (e.g. localhost/path/to/root/index.php is your main page) or you want your code to be valid if that is the case, you will need to add /path/to/root/ before each resource link. You can do this by first storing the path to your website root from your server root and then adding it in front of all your resources links.

In your main index.php file :

$webRoot = realpath(dirname(__FILE__));
$serverRoot = realpath($_SERVER['DOCUMENT_ROOT']);
if ($webRoot === $serverRoot) 
  $pathToWebRoot = "";
else
  $pathToWebRoot = substr($webRoot, strlen($serverRoot) + 1);

...

echo "<link rel='stylesheet' href='$pathToWebRoot/css/main.css'>";
//Or
<link rel="stylesheet" href="<?= $pathToWebRoot ?>/css/main.css">
Adrien
  • 497
  • 4
  • 9