Always use `/` as directory separator in php

c33s

Julian

Posted on May 21, 2018

Always use `/` as directory separator in php

as a long time windows user and php developer, i can only say: do not use DIRECTORY_SEPARATOR! it has no real benefit but really can break things.

use /. it is the better choice nearly every time.

yes it break things!

if you use DIRECTORY_SEPARATOR, which resolves to \ on windows, things tend to break. For example:\ gets converted to %5C in urls.



http://example.com/media/cache/resolve/my_thumb/d/0/1%5Cfilename.jpg


Enter fullscreen mode Exit fullscreen mode

if DIRECTORY_SEPARATOR is used, it easily happens that the (relative) path, which will contain a backslash on windows, is passed to something which should be a url. assuming that most of the php developers are using linux or mac (i personally don't know many people who develop php on windows), they don't notice that in a windows environment a backslash is passed to the url and gets escaped as %5C which leads to urls like in the example above.

windows and php on windows are capable of opening files with the path foo/bar\example/test.txt
so DIRECTORY_SEPARATOR is of no real use except for easily detecting windows or for example if you export a path for a file list where a windows user would be confused to see / instead of \



λ cat ./foo/bar\example/test.txt
mycontent


Enter fullscreen mode Exit fullscreen mode

(yes cat exists on windows)



notepad ./foo/bar\example/test.txt


Enter fullscreen mode Exit fullscreen mode

also opens the file

foo.php:



<?php
$content = file_get_contents('foo/bar\example/test.txt');
var_dump($content);


Enter fullscreen mode Exit fullscreen mode


λ php foo.php
C:\test\foo.php:5:
string(9) "mycontent"


Enter fullscreen mode Exit fullscreen mode

even that works:



<?php
$content = file_get_contents('c:/foo/bar\example/test.txt');
var_dump($content);


Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
c33s
Julian

Posted on May 21, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related