Hướng dẫn php get home directory

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

asked Dec 12, 2009 at 22:33

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'].

answered Dec 12, 2009 at 22:46

Hướng dẫn php get home directory

Felix KlingFelix Kling

769k171 gold badges1068 silver badges1114 bronze badges

8

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


answered Aug 4, 2011 at 18:54

EJ CampbellEJ Campbell

6555 silver badges4 bronze badges

2

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

answered Jun 18, 2015 at 22:22

Francisco LuzFrancisco Luz

2,5732 gold badges24 silver badges35 bronze badges

6

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;
}

answered Sep 11, 2015 at 16:46

ya.teckya.teck

1,80227 silver badges32 bronze badges

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 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;
}

answered Jan 21, 2018 at 14:14

Christos LytrasChristos Lytras

34.7k4 gold badges70 silver badges103 bronze badges

7

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.

Hướng dẫn php get home directory

Tim Cooper

153k37 gold badges320 silver badges272 bronze badges

answered Jul 26, 2011 at 18:42

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;
}

answered Nov 12, 2020 at 19:39

1

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.

answered Mar 8, 2018 at 17:40

Hướng dẫn php get home directory

dustbusterdustbuster

71.9k7 gold badges19 silver badges38 bronze badges

1

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

answered Jul 4, 2020 at 14:43

lisandrolisandro

3862 silver badges10 bronze badges

1

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 :

Hope this answer help you.

answered Nov 24, 2020 at 7:28

Hướng dẫn php get home directory

$_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]

answered Mar 20, 2015 at 18:17

Hướng dẫn php get home directory

iateadonutiateadonut

1,66416 silver badges27 bronze badges

1

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

phant0m

16.3k5 gold badges47 silver badges81 bronze badges

answered Nov 29, 2012 at 18:39

2

answered Dec 12, 2009 at 22:42

streetparadestreetparade

31.1k36 gold badges100 silver badges123 bronze badges

1