views:

71

answers:

2

Ok say I have a code base that is contained in a folder /myProgram/ and has various folders such as /myProgram/lib/, /myProgram/docs/ and so on...

How, in PHP, can I go about detecting any folders before /myProgram/ and creating a base variable so my includes and require's can be written relative to the base directory /myProgram/ allowing me to place myProgram in anything such as root, my home dir, /path/to/myProgram/, and so on?

Doesn't need to work in windows, just a *nix environment. This is all from the command line parser or executable scripts.

A: 

I would suggest using relative paths from the current file like so:

include (dirname(__FILE__).'/../includes/something.inc.php');

This get around hard coding a directory name that might change. As a benefit, this should work on any system.

You can also do something similar to this:

 // In MyProgram/includes/config.php for instance:
 define("BASE_DIR", realpath(dirname(__FILE__).'/../..');

And then you can use the following:

 include(BASE_DIR.'/includes/class.php');

I would strongly advise against any solution that involves hardcoding the name of the directory your application is in.

Matthew Scharley
anyway I can get around it? I really would like to build the includes and requires from the root dir myProgram up. Something like a $HOME/myProgram/... setup.
Urda
@Urda: Check out my edits.
Matthew Scharley
A: 

Here is how I did it... Exactly what I wanted! Figured it out after some playing around with my Program.

// START Directory Bootstrap
$location = dirname(__FILE__);
$rootLoc = strpos($location, "myProgram");
if($rootLoc === FALSE)
    die("WARNING! myProgram Root Directory Not Found!\n");
$root = substr($location, 0, $rootLoc);
$root .= "myProgram";
// Change Directory for working includes and requires.
chdir($root);

This locates where the launching script is, and then attempts to find the base directory. If it can't find the base "myProgram" I assume that the script was placed in the wrong location and needs to fail out. Otherwise it creates a sub-string of everything up to myProgram, then tacks on myProgram at the end. Finally we change directories to allow for includes and requires such as...

include_once("config/serverSettings.php");
require_once("config/mySQLSettings.php");

Legal commands. This is what I was looking for, and I ended up deciding to upload it for others to see.

Urda
So /path/to/myProgram/config/ can be reached just by using "config/mySQLSettings.php" assuming you used the chdir command right away like I did.
Urda
What happens if I move your program to `/path/to/my_program/` instead because I happen to like that naming structure better?
Matthew Scharley
The just change `$rootLoc = strpos($location, "myProgram");` to `$rootLoc = strpos($location, "my_program");` And update`$ .= "myProgram";` to `$root .= "my_program";` Basically update all references to `myProgram` to `my_program` in your bootstrap app.
Urda