Last Updated: February 25, 2016
·
2.511K
· samdev

[PHP] Directory Slash For Cross Platform

Hello CoderZ,

Sometimes we need to let our scripts / codes available and works on every platform ( Unix, Windows, ... etc ) . But to do this we need to consider the difference between this platforms . Of course there is many differences but today we gonna talk about one of them . That is the Directory Slash or Directory Separator whatever you call it .

You may know that Windows uses ( \ ) as the directory slash/separator while Linux uses ( / ) . So what we gonna do ?

It's simpler as you think . Today i'm gonna talk about ( 2 ) method to achieve this . And in the end i will tell you a lil secret .

1st. The Old Fashion Method :

if (strtoupper(substr(PHP_OS,0,3)) == 'WIN') {
 // Windows
 define('SLASH', '\\');

} else {
 // Linux/Unix 
 define('SLASH', '/');
}

Then we use SLASH constant as separator like this :

$file = 'folder_1'.SLASH.'folder_2'.SLASH.'file.php';

2nd. The Official Method :

Using the predefined constant ( DIRECTORY_SEPARATOR ) . Like This :

$file = 'folder_1'.DIRECTORY_SEPARATOR.'folder_2'.DIRECTORY_SEPARATOR.'file.php';

In the end , i wanna tell you a lil secret .

The Secret That Revealed :

Yes Windows use ( \ ) but it doesn't mind if you use ( / ) . So you can use it like this :

$file = 'folder_1/folder_2/file.php';

And it will work well .

Good Luck.