How to get the home directory from a PHP CLI script?

Php

Php Problem Overview


From the command line, I can get the home directory like this:

~/

How can I get the home directory inside my PHP CLI script?

#!/usr/bin/php
<?php
echo realpath(~/);
?>

Php Solutions


Solution 1 - Php

Use $_SERVER['HOME']


Edit:

To make it complete, see what print_r($_SERVER)gave me, executed from the command line:

Array
(
    [TERM_PROGRAM] => Apple_Terminal
    [TERM] => xterm-color
    [SHELL] => /bin/bash
    [TMPDIR] => /var/folders/Lb/LbowO2ALEX4JTK2MXxLGd++++TI/-Tmp-/
    [TERM_PROGRAM_VERSION] => 272
    [USER] => felix
    [COMMAND_MODE] => unix2003
    [__CF_USER_TEXT_ENCODING] => 0x1F5:0:0
    [PATH] =>/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/texbin:/usr/X11/bin
    [PWD] => /Users/felix/Desktop
    [LANG] => de_DE.UTF-8
    [SHLVL] => 1
    [HOME] => /Users/felix
    [LOGNAME] => felix
    [DISPLAY] => /tmp/launch-XIM6c8/:0
    [_] => ./test_php2
    [OLDPWD] => /Users/felix
    [PHP_SELF] => ./test_php2
    [SCRIPT_NAME] => ./test_php2
    [SCRIPT_FILENAME] => ./test_php2
    [PATH_TRANSLATED] => ./test_php2
    [DOCUMENT_ROOT] => 
    [REQUEST_TIME] => 1260658268
    [argv] => Array
      (
        [0] => ./test_php2
      )

    [argc] => 1
    )

I hope I don't expose relevant security information ;)

Windows Compatibility

Note that $_SERVER['HOME'] is not available on Windows. Instead, the variable is split into $_SERVER['HOMEDRIVE'] and $_SERVER['HOMEPATH'].

Solution 2 - Php

You can fetch the value of $HOME from the environment:

<?php
    $home = getenv("HOME");
?>

Solution 3 - Php

PHP allows you to get the home dir of any of the OS users. There are 2 ways.

Method #1:

First of all you gotta figure out the OS User ID and store it somewhere ( database or a config file for instance).

// Obviously this gotta be ran by the user which the home dir 
// folder is needed.
$uid = posix_getuid();

This code bit can be ran by any OS user, even the usual webserver www-data user, as long as you pass the correct target user ID previously collected.

$shell_user = posix_getpwuid($uid);
print_r($shell_user);  // will show an array and key 'dir' is the home dir

// not owner of running script process but script file owner
$home_dir = posix_getpwuid(getmyuid())['dir'];
var_dump($home_dir);

Documentation

Method #2:

Same logic from posix_getpwuid(). Here you gotta pass the target OS username instead of their uid.

$shell_user = posix_getpwnam('johndoe');
print_r($shell_user); // will show an array and key 'dir' is the home dir

// not owner of running script process but script file owner
$home_dir = posix_getpwnam(get_current_user())['dir'];
var_dump($home_dir); 

Documentation

Solution 4 - Php

This function is taken from the Drush project.

/**
 * Return the user's home directory.
 */
function drush_server_home() {
  // Cannot use $_SERVER superglobal since that's empty during UnitUnishTestCase
  // getenv('HOME') isn't set on Windows and generates a Notice.
  $home = getenv('HOME');
  if (!empty($home)) {
    // home should never end with a trailing slash.
    $home = rtrim($home, '/');
  }
  elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
    // home on windows
    $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
    // If HOMEPATH is a root directory the path can end with a slash. Make sure
    // that doesn't happen.
    $home = rtrim($home, '\\/');
  }
  return empty($home) ? NULL : $home;
}

Solution 5 - Php

If for any reason getenv('HOME') isn't working, or the server OS is Windows, you can use exec("echo ~") or exec("echo %userprofile%") to get the user directory. Of course the exec function has to be available (some hosting companies disable that kind of functions for security reasons, but that is more unlikely to happen).

Here is a [tag:php] function that will try $_SERVER, getenv and finally check if the exec function exists and use the appropriate system command to get the user directory:

function homeDir()
{
    if(isset($_SERVER['HOME'])) {
        $result = $_SERVER['HOME'];
    } else {
        $result = getenv("HOME");
    }
        
    if(empty($result) && function_exists('exec')) {
        if(strncasecmp(PHP_OS, 'WIN', 3) === 0) {
            $result = exec("echo %userprofile%");
        } else {
            $result = exec("echo ~");
        }
    }

    return $result;
}

Solution 6 - Php

Depends on where you are and what you're trying to do.

$_SERVER is completely unreliable for a non-server script, BUT $_ENV['HOME'] might be better for a standard shell script. You can always print_r( $GLOBALS ) and see what your environment gives you to play with. phpinfo() also spits out plaintxt when called from a CLI script, and just good ole php -i executed from a shell will do the same.

Solution 7 - Php

This works for me both LINUX and WINDOWS:

function get_home_path() {
  $p1 = $_SERVER['HOME'] ?? null;       // linux path
  $p2 = $_SERVER['HOMEDRIVE'] ?? null;  // win disk
  $p3 = $_SERVER['HOMEPATH'] ?? null;   // win path
  return $p1.$p2.$p3;
}

Solution 8 - Php

This is the method i used in a recent project:

exec('echo $HOME')

I saved it into my object by doing this:

$this->write_Path  = exec('echo $HOME');

But you could really save it any way you want and use it anyway you see fit.

Solution 9 - Php

You can rely on "home" directory when working with web server. Working CLI it will give the user path (in windows) if you want your script to work in web and cli environments I've found better to go up any levels with dirname until your root(home) directory.

echo dirname(__DIR__).PHP_EOL; // one level up
echo dirname(dirname(__DIR__)); //two levels up
echo dirname(__DIR__,2).PHP_EOL; //two levels only php >7.0

Solution 10 - Php

I know that this is an old question, but if you are looking for an alternative and easy to replicate method across your application, you may consider using a library installed via composer. I've written a library that combine some of the answer here and make it a library and I'll shamelessly promote it here : juliardi/homedir.

You can install it via composer :

$ composer require juliardi/homedir

And then use it in your application :

<?php

require_once('vendor/autoload.php');

$userHomeDir = get_home_directory();

Hope this answer help you.

Solution 11 - Php

$_SERVER['HOME'] and getenv('home') did not work for me.

However, on PHP 5.5+, this worked to give the home directory that the file is located in:

explode( '/', __FILE__ )[2]

Solution 12 - Php

Try $_SERVER['DOCUMENT_ROOT'] as your home directory.

Solution 13 - Php

dirname(__DIR__);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - PhpFelix KlingView Answer on Stackoverflow
Solution 2 - PhpEJ CampbellView Answer on Stackoverflow
Solution 3 - PhpFrancisco LuzView Answer on Stackoverflow
Solution 4 - Phpya.teckView Answer on Stackoverflow
Solution 5 - PhpChristos LytrasView Answer on Stackoverflow
Solution 6 - PhpJess PlanckView Answer on Stackoverflow
Solution 7 - PhpVladimir BuskinView Answer on Stackoverflow
Solution 8 - PhpdustbusterView Answer on Stackoverflow
Solution 9 - PhplisandroView Answer on Stackoverflow
Solution 10 - PhpardiView Answer on Stackoverflow
Solution 11 - PhpiateadonutView Answer on Stackoverflow
Solution 12 - PhpBlackLeadPencilView Answer on Stackoverflow
Solution 13 - PhpstreetparadeView Answer on Stackoverflow