Andrew
Andrew

Reputation: 238707

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

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(~/);
?>

Upvotes: 73

Views: 95457

Answers (13)

Felix Kling
Felix Kling

Reputation: 816404

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'], meaning if you want both Unix-and-Windows compatibility, do:

$homepath = $_SERVER['HOME'] ?? (/*windows compatibility: */$_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']);
// $homepath looks like /home/username or C:\Users\username

Upvotes: 91

ardi
ardi

Reputation: 3

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.

Upvotes: -3

Vladimir Buskin
Vladimir Buskin

Reputation: 624

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

Upvotes: 2

lisandro
lisandro

Reputation: 496

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

Upvotes: -1

Francisco Luz
Francisco Luz

Reputation: 2943

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

Upvotes: 11

dustbuster
dustbuster

Reputation: 82152

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.

Upvotes: -1

Christos Lytras
Christos Lytras

Reputation: 37308

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

Upvotes: 5

ya.teck
ya.teck

Reputation: 2336

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

Upvotes: 9

iateadonut
iateadonut

Reputation: 2239

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

Upvotes: -7

BlackLeadPencil
BlackLeadPencil

Reputation: 1

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

Upvotes: -11

Jess Planck
Jess Planck

Reputation: 31

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.

Upvotes: 2

EJ Campbell
EJ Campbell

Reputation: 725

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

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

Upvotes: 69

streetparade
streetparade

Reputation: 32888

dirname(__DIR__);

Upvotes: -18

Related Questions