Issue
I've understood there are several ways to determine the user's home, depending on the platform (mainly Unix/Linux vs Windows).
Composer uses an environment variable, in composer/Platform package:
public static function getUserDirectory()
{
if (false !== ($home = getenv('HOME'))) {
return $home;
}
if (self::isWindows() && false !== ($home = getenv('USERPROFILE'))) {
return $home;
}
if (function_exists('posix_getuid') && function_exists('posix_getpwuid')) {
$info = posix_getpwuid(posix_getuid());
return $info['dir'];
}
throw new \RuntimeException('Could not determine user directory');
}
public static function isWindows()
{
return defined('PHP_WINDOWS_VERSION_BUILD');
}
Webmozart's path-util package uses other environment variables:
public static function getHomeDirectory()
{
// For UNIX support
if (getenv('HOME')) {
return static::canonicalize(getenv('HOME'));
}
// For >= Windows8 support
if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) {
return static::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH'));
}
throw new RuntimeException("Your environment or operation system isn't supported");
}
What is the difference between these two methods? Is one more reliable than the other? Note: I'm using PHP in the CLI, so it's always the actual current user running PHP.
EDIT> I understand that this question seems to ask for an opinion, but it's not the case. I DO NOT KNOW Windows and do not understand why some packages use different ways to determine the user's home directory. I'm asking for explanations about the two mentioned methods: is one of them more reliable than the other and why? I've edited the title and the question to reflect this precision.
Solution
After not working on this for a long time, I finally decided to definitely answer this question.
There are some usefull environment variables defined on Windows: USERPROFILE
, APPDATA
, LOCALAPPDATA
. They are easily accessible via getenv() function:
getenv('USERPROFILE');
USERPROFILE
exists on any Windows, according to https://docs.microsoft.com/fr-fr/windows/desktop/shell/knownfolderid
So, on Windows, it seems to be reliable.
If you need to store data for the current user, APPDATA
and LOCALAPPDATA
are good variables to find that place.
I've written a package to make these tools reusable: https://github.com/Arcesilas/Platform
It's still work in progress and certainly needs to be improved. Any help is welcome to make this tool reliable on any platform.
Thanks to eryksun whose comments helped a lot in solving this question.
Answered By - Arcesilas Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.