Advantage of relative to absolute roots?

Hello,

I’m not having any code issues per se, but do have a question more about cleanliness of code. Now at the tail end of my first big experience with php/designing a site, I’m reflecting on some efficiency issues. One issue that’s come up is whether it would have been more efficient to use absolute instead of relative paths.

For example, I originally wrote

if ($member_logged_in)  {
	if ($parts[1] == "index.php") {
		include('includes/all_pages_nav_left.php');
} elseif ($parts[1] == "Chapters") {
	include('../../includes/all_pages_nav_left.php');
} elseif ($parts[1] == "Students" || $parts[1] = "Instructors") {
	include('../includes/all_pages_nav_left.php');}
}
if (!($member_logged_in)) {
	if ($parts[1] == "index.php") {
		include('includes/index_nav_left.php');
	} elseif ($parts[2]=="Homepage" || $parts[2] =="Linear_Functions") {
	include('../../includes/index_nav_left.php');
} elseif ($parts[1] == "Students") {
	include('../includes/index_nav_left.php');}
	

}

which works just fine. But, now I’ve “discovered” $_SERVER[DOCUMENT_ROOT] and the code

if ($member_logged_in) {
	include ($_SERVER['DOCUMENT_ROOT'] . '/includes/all_pages_nav_left.php');
} else {
	include ($_SERVER['DOCUMENT_ROOT'] .
	'/includes/index_nav_left.php');
	}

seems to work just as well. Initially, Ithought that I’d have to hard-code the absolute path: with different servers (local vs. remote for example), it would have been a nightmare. But with the $_SERVER variable, I think that there’s no reason that I ever should have used relative paths for anything such as above.

So, my question is whether there would ever be compelling reason to use relative over absolute paths with PHP…

Thanks!

-Eric

Include directories ought to be out of sight of your web doc root.

/stuff/includes/secret.php <-your database login details
/stuff/includes/nav/page_left.php <-your database login details
/stuff/webroot/index.php <-your ‘home page’

if you then set your ini file to have include_path = /stuff/includes

using something like ini_set() or something in your .htaccess or you DO have control over your ini file - from then on you just do;

Then in index.php or even deep in directories like /stuff/webroot/articles/index.php


<?php
include 'secret.php';
include 'nav/page_left.php';
?>

Then you can stop worrying about include files.

Read about what can be set where on this man page:

PHP: List of php.ini directives - Manual

Or read this discussion from earlier today:

Ahhh the hours of agony that this would have saved me. :slight_smile:

The world of the PHP newbie is fraught with peril…

Thanks for the helpful tip.

We’ve all been there… I hope my tip helps you and saves you the long and sometimes stupidly shallow learning curve I followed.

You’ll do well if you ask more questions like this one - I wish to hell I had.

:slight_smile:

Happy Friday!