Reputation: 3407
I am using PHP for a command line tool that I am building. My tool has to work both on Windows and *NIX based systems. My primary development environment in Ubuntu Linux.
I was wondering whether I should take care of handling directory separator my self every time I do something with files or would PHP take care or that for me? For example:
In Linux:
$user_home = get_user_home_folder();
$filePath = "{$user_home}/path/to/file.txt";
Would the code above work on Windows without modification or should I always do something like:
$user_home = get_user_home_folder();
$filePath = "{$user_home}/path/to/file.txt";
if(is_windows_os()) {
$filePath = str_replace('/','\\',$filePath);
}
Any advice is very much appreciated.
Upvotes: 0
Views: 133
Reputation: 98861
This will work for you:
<?
$filePath = "/path/to/file.txt";
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
//windows
$filePath = getenv('HOME').str_replace("/", "\\", $filePath);
echo $filePath;
} else {
//linux
$user_home = get_user_home_folder();
$filePath = $user_home.$filePath;
echo $filePath;
}
?>
In my case (windows) outuputs:
C:\Users\Administrator\path\to\file.txt
Notes:
I never heard about a php function called get_user_home_folder()
I assume it's a custom function.
Upvotes: 1
Reputation: 347
This maybe help you.
define('DS', is_windows_os() ? '\\' : '/');
$user_home = get_user_home_folder();
$filePath = $user_home.DS."path".DS."to".DS."file.txt"
Use constant DS for path and will be automatically change on need separator
Upvotes: 1
Reputation: 229
PHP will try to convert '/' to the correct separator when it can. It also provides a builtin constant called DIRECTORY_SEPARATOR
if you don't want to rely on that behaviour.
That constant and the join
function work well together for building paths.
e.g. $fullPath = join(DIRECTORY_SEPARATOR, [$userHome, 'path', 'to', 'file.txt']);
Upvotes: 1