Using relative paths with PHP include function.
Using a development and production server with different configurations. Is forcing me to update my paths every time. And, by default, PHP will not support relative paths for includes like (X)HTML does.
Well after foraging around on the internet, I found many ways to achieve this. Most of them were over complicated. Requiring you to write scripts to detect the level of the page that needed to include a file and appending ‘./’ or ‘../’ etc to the include path, others included creating a class with the servers address and then prepend that to the include path.
Why I didn’t like it - extra mark-up! I hate having to create extra and unnecessary mark-up in my code, I aim to have my code as clear and as clean as I can.
So I took a time out to review what I was trying to achieve, and after about 2 minutes I remembered the predefined variable $_SERVER. By teaming this up with DOCUMENT_ROOT you will get - $_SERVER[‘DOCUMENT_ROOT’]. You can then use this to output the document root directory under which the current script is executing, as defined in the server’s configuration file. Right here you have a nifty little bit of portable code.
You have to make sure that when teaming it up with a path you use ‘.’ to combine the variable with the path. Like so - $_SERVER[‘DOCUMENT_ROOT’].’/includes/includeme.php’
So now instead of having paths like (‘/home/user/www/includes/includeme.php’) I can now use ($_SERVER[‘DOCUMENT_ROOT’].’/includes/includeme.php’) and it will work seamlessly on my development server and production server. Nice!
I am sure that this will come in handy in other instances, so remember not to overlook the basics. Sometimes we over complicate things, when they needn’t be.