Search code examples
phplinuxshellubuntuhome-directory

How to find path of user's home directory in PHP Cli on linux?


I am trying to write an script to check a particular directory exits or not on current logged in user's home directory via PHP.

when on terminal I use

    cd ~
    pwd

It shows /home/ramratan.

But when I tried via PHP the same thing like below

    chdir("~");
    PHP Warning:  chdir(): No such file or directory (errno 2) 
    in php shell code on line 1
    PHP Stack trace:
    PHP   1. {main}() php shell code:0
    PHP   2. chdir() php shell code:1

I also tried below

 chdir("/home");
 echo shell_exec("pwd");

It displays /home not /home/ramratan, if someone help me what should I do in chdir("/home") so that it returns /home/ramratan.

I have also tried below but no success

 chdir("/home/".shell_exec("whoami"));
 PHP Warning:  chdir(): No such file or directory (errno 2) 
 in php shell code on line 1
 PHP Stack trace:
 PHP   1. {main}() php shell code:0
 PHP   2. chdir() php shell code:1

Solution

  • You can find the current username by using whomai as you already wrote. Use that name to find the line corresponding to that user in /etc/passwd. From that line cut out the home dir information:

    $currentUserHomeDir = exec('grep `whoami` /etc/passwd | cut -d ":" -f6');