PHP Stuff

Okay, so this morning I was playing with something on a web app I’ve written. Previously it had been very clumsily written (and not modular at all) and over past weeks I’ve been busily rewriting it in a sort of semi MVC pattern. I looked at using one of the prewritten frameworks out there (and played with Kohana quite a bit a few months ago) but decided it would be too much work to learn all the conventions, rewrite my database structure to meet Kohana’s ORM standards, and it was just way overkill for what I needed. But anyway I digress.

In writing new classes for a lot of my functions I found that I would need to get the base path of where the app is installed (and it will vary depending on whether it’s being hosted on a Windows or Linux box). So with a little of this function that I found on some mailing list somewhere:

//Are we on Windows or *NIX ??
function platform() {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
return 'windows'; } else return 'linux';
}

I was then able to write this little function which gets the base path of the installation (bearing in mind that it is always called from a directory which is one folder lower than the base path). For example this function resides in C:\xampp\htdocs\myapp\functions\functions.php – and returns a value of C:/xampp/htdocs/myapp .

//Get the base path
function basepath() {
$os = platform();
$dir_separator = ($os == 'windows') ? '\\' : '/';
$path = explode($dir_separator, __FILE__);
$path = array_slice($path, 0, -2);
return ($os == 'windows') ? implode('/', $path) : '/' . implode($dir_separator, $path);
}

Basically… get the absolute path to the file it’s being called from… split it into an array of segments using explode()… slice the last 2 elements off the end of the array, and then put it all back together again.

There are probably more elegant ways of doing this, which I’m open to looking at.. but this is certainly doing the job.

Leave a comment

0 Comments.

Leave a Reply

You must be logged in to post a comment.