Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP. Get user home directory (for virtual hosting)

Tags:

shell

php

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

like image 702
indapublic Avatar asked Dec 12 '13 05:12

indapublic


3 Answers

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'].

like image 74
indapublic Avatar answered Oct 18 '22 01:10

indapublic


Use $_SERVER['HOME'] or you try with

$home = getenv("HOME");

Note: This require that you execute the script via the command-line.

like image 42
Anish Avatar answered Oct 18 '22 00:10

Anish


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']
like image 26
kwood Avatar answered Oct 18 '22 02:10

kwood