0

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?

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by chrishea
1

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";

Edited by chrishea: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.