PHP Portable Paths

Forward SlashFrankly, I don’t care about people wanting to run my code on a Windows box and it not working. But in reality, for some reason, there are people who write code using computers running the Microsoft Windows operating system. Why don’t they use a Mac, or if they don’t have or want to spend the money on a Mac, use Linux? That I do not know, but there are people, and they probably work in your company who use Windows and they think they can code.

Like I said, I don’t really care if my shit doesn’t run on Windows, but it is relatively trivial to write PHP code that can run on Windows and Linux, Mac and any operating system that can run PHP.

The only real obstacle to portability is directory paths. In my world, these are usually paths to configs or log directories.

The could be code like this.

$config = new Configuration(sprintf('conf/%s', $configFilename));

That’s not portable to Windows because of that forward slash.

What I could do is this.

$config = new Configuration(sprintf('conf%s%s', DIRECTORY_SEPARATOR, $configFilename));

Now instead of a forward slash, if this were running on Windows, it would use a backward slash, because Windows is backwards.

I took it one step more and wrote a static method in my Configuration class that looks like this.

public function static Path($path)
    if (DIRECTORY_SEPARATOR == '/') return $path;
    return str_replace('/', DIRECTORY_SEPARATOR, $path);

This method will replace all forward slashes with DIRECTOR_SEPARATOR. If the DIRECTOR_SEPARATOR is a forward slash, the path is just returned unchanged. If DIRECTOR_SEPARATOR is not a forward slash, forward slashes in path are replaced with what is DIRECTOR_SEPARATOR.

I do it this way because in my code, I still put the forward slash in. The default is that my code will be running on some version of Linux, so the forward slash is correct. But since I pipe my paths through Configuration::Path, if they need to be changed, the directory separator will be changed to the operating system’s appropriate separator.

So in my code, using the Configuration Path static method, I would do something like this.

$config = new Configuration(Configuration::Path(sprintf('conf/%s', $configFilename)));

This pathing issue alone doesn’t make your code automatically 100 percent portable. There are issues with specific PHP functions that may require different things to happen when your code is running on Windows or Linux. But the pathing issue is the easiest to do correctly.

Share Button