Include and Require question

My web root consists of a bunch of files and 1 or 2 directories. There’s an admin directory and an includes directory. In the includes directory, I have your basic include files (i.e. - header.php, footer.php, etc.) and in the admin directory, I have the index page for when someone’s logged-in.

I’m having problems using include() and require() correctly. I’ve included / required my header.php in the web root’s homepage and it’s working accordingly as the include address is “includes/header.php”, but when I log-in and try to view the admin’s homepage, it’s lost.

I know this is an issue with addressing and I get that, but my question here pertains to how this is solved on a multi-directory inclusion sense. In other words, how do I include a single include file within different pages that belong to different directories? I tried doing something like “require $home_url.‘/includes/.header.php’;” but it broke due to server configurations for direct linking.

You can use an absolute path on the server:


Of course this will almost certainly break if you move web hosts or if the host decides to modify the server structure.

A better idea is to use relative paths:

//From webroot/directory/script.php
//Including webroot/includes/header.php


Of course this requires that the PHP process’ current working directory is set to the same as the script, which is a dangerous assumption to make. This will break if you include a file in a different directory which includes yet another file in another different directory.

This is a more bullet-proof method which combines the strengths of the absolute and relative path methods:

//From webroot/directory/script.php
//Including webroot/includes/header.php


I would use Tarh’s recommendation and use the


format. It is the most reliable, especially if you end up moving hosts, or changing your base directory.

Are there any cons to defining directory constants this way to make for easier addressing to resources?

According to

Given a string containing the path of a file or directory, this function will return the parent directory’s path.

So, as long as PHP is functioning correctly, the dirname function should always return the correct path relative to the file.

The dirname(FILE) method is very widely used and I have not yet come across anyone having issues with it.