How can I define the DIRECTORY_SEPARATOR for both Windows and Linux platforms?

Viewed 44420

Now I create a small PHP Application, here I have problem for using file path, because in Windows use this type location C:\Some\Location\index but in Linux /www/app/index so when I define the path using this / but when the application run in window machine it should be problem for this /.

So here I want to define the DIRECTORY_SEPARATOR both Windows and Linux platform.

7 Answers

Try this for window

defined ('DS') ? null : define('DS', DIRECTORY_SEPARATOR);

define( 'SITE_ROOT',  DS . 'xampp' . DS .'htdocs' .  DS .'gallery');

This is messy, would you agree?

$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';

So just do this:

$file = 'path/to/file';

It works on Windows, Linux, Mac altogether. Backslash however only works on Windows and needs to be escaped \\ so try to avoid them. :)

To turn a file referenced by PHP on Windows into forward slahes, use str_replace. Here is an example:

$dir = str_replace('\\', '/', realpath('../'));
Related