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