Home > Programming > A few useful tidbits of PHP

A few useful tidbits of PHP

I was fooling around with some stuff when I noticed one of the scripts I was trying to use had some hard-coded paths in it meaning I couldn’t rename it’s base directory (which really wasn’t a good name to begin with). Anyways, I thought I’d post a few simple things every PHP programmer can add to their repository of useful junk which may help them deal with using relative paths to include files in both their PHP scripts and any HTML pages that need relative source paths too.

First, one of the most useful things you may come across is simply adding this one line and then using __PATH__ in your code where you need it:

define('__PATH__', dirname(__FILE__));

This gives you a new constant, __PATH__, which will be the full directory part of __FILE__. This saves you writing dirname(__FILE__) all over the place since you will no doubt end up using that if you use any sort of relative path include system. Oh and yes I know it’s “bad practice” to define something like __PATH__, but the nice part is that if PHP ever does implement that constant – it should be what we have it as right now, so you just remove the define() statement and be on your merry way.

The second useful thing to add is a function which helps you in crafting relative URLs (though I’m sure it can be used elsewhere too):

function basepath($source, $search = '') {
$source = strtr($source, DIRECTORY_SEPARATOR, '/');
return substr($source, strpos($source, $search) + strlen($search));
}

You pass the function a path to a file and a string to search for in that path. If it finds the search string, it removes it and everything before it in the path and returns what’s left. So, say you called it as basepath(__FILE__, ‘/public_html/’) and __FILE__ was something like ‘/home/username/public_html/website/includes/file.php’, it would return ‘website/includes/file.php’. Since you will no doubt know the name of a parent path somewhere a long the lines, you can use that to strip out what you already know (so in this case, the non-url portion of a URL for your site) and end up with a path a client browser can access.

I’ll leave it up to you to see how useful these may be and how you want to use them – but the purpose is to remind you to never hard code paths if you can avoid it – especially if it’s a 3rd party addon (like themes and plugins for WordPress, for example).

Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.