From the command line, I can get the home directory like this:
~/
How can I get the home directory inside my PHP CLI script?
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.
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;
}
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;
}
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
$_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]
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.