I learned from distributing code that the best way for your application to run on both Linux and Windows is to never use DIRECTORY_SEPARATOR, or backslashes \\
, and to ONLY use forward slashes /
.
Why? Because a backslash directory separator ONLY works on Windows. And forward slashes works on ALL (Linux, Windows, Mac altogether).
Using the constant DIRECTORY_SEPARATOR or escaping your backslashes \\
quickly becomes messy. I mean look at it:
$file = 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'file';
$file = str_replace('/', DIRECTORY_SEPARATOR, 'path/to/file';
$file = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'path\\to\\file' : 'path/to/file';
When you can just do this:
$file = 'path/to/file';
The only downside is that on Windows; PHP will return backslashes for all file references from functions like realpath()
, glob()
, and magic constants like __FILE__
and __DIR__
. So you might need to str_replace()
them into forward slashes to keep it consistant.
$dir = str_replace('\\', '/', realpath('../'));
I wish there was a php.ini setting to always return forward slashes.
windows
understands the use of '/' as the directory separator. I run PHP code on both linux and windows without any change. I use '/' always in file paths etc. The main issue is thatwindows
is not case sensitive as regards filenames so it is important to always use correct lettercase on windows otherwise it will not work when moved tolinux
, – Hydromedusashell_exec
a command which contains a path you will need the DIRECTORY_SEPARATOR to build that path in Windows. – Edible