PHP. Get user home directory (for virtual hosting)
Solution 1
I founded working solution:
$user = posix_getpwuid(posix_getuid())
This returns the array, e.g.
Array
(
[name] => username
[passwd] => ********
[uid] => 501
[gid] => 20
[gecos] => Full Name
[dir] => /home/username
[shell] => /bin/bash
)
So to access user home dir, it's $user['dir']
.
Solution 2
Use $_SERVER['HOME']
or you try with
$home = getenv("HOME");
Note: This require that you execute the script via the command-line.
Solution 3
On most regular servers, those daemons (apache, nginx, etc.) have no real "home directory".
If you consider "virtual hosting", that wouldn't be possible, as there can only be one home directory per user, but many vhosts per daemon.
I guess what you are looking for, ist the environment variable DOCUMENT_ROOT (the root directory for the current vhost documents).
$_SERVER['DOCUMENT_ROOT']
indapublic
Updated on June 16, 2022Comments
-
indapublic almost 2 years
I want to get home directory of current script user (nginx/www/apache etc.) in PHP. I use
$output_message = shell_exec('echo ~'); var_dump($output_message);
It's working correctly on my local server, on Amazon instances. But it outputs only "~" on virtual hosting.
Maybe, do you have working solution for getting home directory of current user?
Thanks in advance
-
indapublic over 10 yearsgetenv returns FALSE. $_SERVER['HOME'] is not exists (Notice: Undefined index: HOME)
-
Travis over 8 yearsBoth examples in @Anish's answer require that you execute the script via the command-line
-
Markus Zeller over 5 yearsOn windows you can use
$home = getenv("USERPROFILE")
.