0

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.

2
  • 1
    Not sure about the older versions of Windows, but / works in Windows 7 and above Commented Jan 25, 2014 at 14:28
  • Thank you. you hint helped very much :) Commented Jan 26, 2014 at 1:16

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

get_user_home_folder is a custom function :)
@gevik you need to check the correct sign in order to mark the answer as correct ;)
1

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']);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.