Helpful Shortcut for PHP Directory Separator Constant

Published on 21st Apr, 2015

This is just a quick post. I'd like to share a method I've been using for quite some time.

Often I'm including files in PHP in cross-platform situations. So for Windows I'd be including a '\' and in any other system it'd be a '/' when I'm constructing my file paths. Well PHP provides a handy constant for you:

DIRECTORY_SEPARATOR;

So when you're building a path you can just do:

$path = 'app' . DIRECTORY_SEPARATOR . 'file.php';

This is nice for portability, as PHP will determine what system you're on and insert the appropriate separator. However I found it ugly and, frankly, tiresome to type all the time. I would store it on my clipboard as much as possible but that rarely lasts long.

So I found this snippet that the wonderful folks who wrote Joomla! (and likely other places) implement:

define("DS", DIRECTORY_SEPARATOR);

So now we have:

$path = 'app' . DS . 'subfolder' . DS . 'file.php';

Lovely! I'm certainly not the only one doing this and this isn't some magically original idea. I just tend to write into the top of ANY project I'm working on and it makes my life better. So I thought I'd share.

Take care.

This article is my 24th oldest. It is 201 words long

comments powered by Disqus