Getting Relative Paths in PHP

OK, so I realize that:

$_SERVER['PATH_TRANSLATED'];

No longer works on Apache 2. I figured out a way to get the paths and take out the actual filename at the end.

function getDir() {
$expl = explode("/",$_SERVER["REQUEST_URI"]);
$count = count($expl)-1;
for($i=1;$i<$count;$i++) {
$id = $expl[$i];
echo "/".$id;
}
echo "/";
}

First, I explode the Request URI into an array. Then I count how many items are in the array, minus one because there is a 0 which is blank. Then I do a loop starting at 1 (since there is nothing in 0) and go until I get to the end. Then I added a “/” at the end to make sure it was a directory. To give an example, if I navigate to http://localhost/pictorials/includes/config.php, it will print out /pictorials/includes/

If you want to make it the full absolute path, you can use $_SERVER['SERVER_NAME']; if you want.

Enjoy!

PS: I am aware that you can easily do it this way:

echo dirname($_SERVER["REQUEST_URI"]);

I just wanted to see how confusing I could make it. I like to obfuscate code šŸ˜‰

Advertisements

About this entry