PHP. Get user home directory (for virtual hosting)

13,780

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']
Share:
13,780
indapublic
Author by

indapublic

Updated on June 16, 2022

Comments

  • indapublic
    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
    indapublic over 10 years
    getenv returns FALSE. $_SERVER['HOME'] is not exists (Notice: Undefined index: HOME)
  • Travis
    Travis over 8 years
    Both examples in @Anish's answer require that you execute the script via the command-line
  • Markus Zeller
    Markus Zeller over 5 years
    On windows you can use $home = getenv("USERPROFILE").