如何高效,快速地编写PHP / HTML中的相对路径?

I've managed to teach myself PHP/PDO/SQL, and yet, I cannot for the life of me figure out how relative paths work in PHP & HTML. I've got a multipage website with a few directories and branches, and I want to be able to create a simple template I can use to make new pages, without having to change the links to my stylesheets and PHP includes every time, depending on directory.

Here's my layout as follows:

 MySite (http://localhost/MySite/)
   RESOURCES //Not a folder, just here for readability
   > serverside > initialize.php
   > templates  > header.php
                  footer.php
                  navuser.php
                  navmenu.php
   > styles     > styles.css
   > images     > variousImages.png

   PAGES //Not a folder, just here for readability

   > index.php
     login.php
     register.php
     gettingstarted.php

  > you         > settings    > settings.php
                > youraccount.php
                > yourfavourites.php

Here are the rules of the game: Each page first includes the serverside/initialize.php file (PHP include). Then, each page includes styles/styles.css through a standard HTML href attribute. Each page then includes via PHP both templates/header.php and templates/footer.php, with the former ALSO containing templates/navuser.php, and templates/navmenu.php.

The problem is, if one of the pages is in on a different level (say you/settings/settings.php, for example), then all those includes and hrefs have to change, which seemingly affects the includes inside the includes. It's impossible!

All I want is to be able to specify file names without using true absolute paths so I can have a single template file to duplicate throughout my website if needed - I've looked into __DIR__, __FILE__, $_SERVER['DOCUMENT_ROOT'], casting a variable $dir to act as a document root, but to no success. I don't understand half of what's happening either.

Can anyone shed some light on my situation? I'm essentially looking for a complete explanation of how relative roots/links/files are meant to work in PHP. How do I deal with even more complex directory structures? Again, what should I do? Thanks.

You would usually set a constant containing an absolute path and absolute URL in your index.php file, and then reference them from there on in includes etc.

An example index.php:

<?php
define('ROOT_DIR', __DIR__);

You can then use that constant thereafter:

require ROOT_DIR . '/includes/database.php';
require ROOT_DIR . '/application/controllers/MyController.php';
require ROOT_DIR . '/application/models/MyModel.php';

And so on. Hope this helps.