I often find myself parsing a url or filepath for includes and links, and it usually leads to messy, frustrating code. Given PHP's massive library, I assumed there would be something to make life easier, but I couldn't find anything while pouring over the online reference. It's a lot of material, though, so I may have missed something. Does anyone know the best way to play with paths?

Here's one example of this problem. I have a navigation template that I include in every page on my site, but the relative links need to be processed to work at different folder depths. For instance, the relative link to mysite.com/folder1/ from mysite.com/ would be "folder1/". From mysite.com/folder2/, it would be "../folder1/". From mysite.com/folder1/page.html, it would be "/".

The script I wrote to perform this function is pretty messy. It involves grabbing the path through $_SERVER, exploding it around "/", finding the depth of current file, and finally adding the necessary "../" to the relative link. I run into situations like this a lot, and I haven't been able to find a general solution thus far. Any tips on the best way to handing path parsing?

There are commands such as parse_url that may help but maybe the solution in this case is to do your addressing differently. If your programs define a session variable that has the base address of the root folder of your application, then you can do all of your includes relative to the root folder and it will be the same include string in every program regardless of where they are nested in your directory structure.

Instead of include "../a.php";
You would use include $base_address."/x/y/a.php";

As a tip, you can also keep a directory of utility routines that can be included in any program on your site in the root of the site. You can get the address of it in any program as follows:

$path_global = $_SERVER."/your common directory name";

You can then get any of these common modules by addressing them as follows:

include $path_global."/b.php";