How to get the home directory from a PHP CLI script?

前端 未结 13 1072
生来不讨喜
生来不讨喜 2020-12-08 03:45

From the command line, I can get the home directory like this:

~/

How can I get the home directory inside my PHP CLI script?



        
13条回答
  •  伪装坚强ぢ
    2020-12-08 04:14

    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

提交回复
热议问题