I needed to locate current user’s home directory, to find and parse a config file like ~/config.ini. The current user is a user that is currently running a PHP CLI script. I have found a neat solution in drush, ready to copy & paste into your function:

  // getenv('HOME') isn't set on windows and generates a Notice.
  $home = getenv('HOME');
  if (empty($home)) {
    if (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
      // home on windows
      $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
    }
  }
  return empty($home) ? NULL : $home;