Forum Moderators: coopster

Message Too Old, No Replies

How important is OS specific DIRECTORY SEPARATOR?

When writing portable code.

         

penders

4:14 pm on Sep 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm all for writing portable code, but how important is using the correct OS DIRECTORY_SEPARATOR in server-side paths?

Under Windows (Apache at least) you seem to be able to interchange '/' (forward slash - unix) and '\' (backslash - windows) in a path and it makes no difference? Is this the same under IIS? (Under Linux you must use a forward slash.)

PHP Manual - dirname [uk2.php.net]
On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

All $_SERVER[] vars like 'DOCUMENT_ROOT', 'SCRIPT_FILENAME' etc. appear to return '/', regardless of OS (under Apache at least). But the magic constant __FILE__ appears to obey the DIRECTORY_SEPARATOR and returns '\' under windows. This seems a bit inconsistent and makes simple string comparison a bit troublesome without first making sure you are comparing like with like (ie. by replacing all '\' with '/' in __FILE__ when under Windows!).

I do use the constant DIRECTORY_SEPARATOR where applicable, but since the $_SERVER[] vars return '/' I end up with a mixture anyway (when testing under Windows).

Any reason not to use '/' (forward slash) ALL the time?

Does IIS work differently in this respect?

Any comments appreciated, thanks.

coopster

7:43 pm on Sep 3, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



As a rule of thumb I use the constant when ever working with file system paths. I build all paths using a slash and then check the
PHP_OS
for stristr("Win"). If I get a hit, I run a regex to convert all slashes to
DIRECTORY_SEPARATOR
.