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

前端 未结 13 1096
生来不讨喜
生来不讨喜 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:18

    If for any reason getenv('HOME') isn't working, or the server OS is Windows, you can use exec("echo ~") or exec("echo %userprofile%") to get the user directory. Of course the exec function has to be available (some hosting companies disable that kind of functions for security reasons, but that is more unlikely to happen).

    Here is a php function that will try $_SERVER, getenv and finally check if the exec function exists and use the appropriate system command to get the user directory:

    function homeDir()
    {
        if(isset($_SERVER['HOME'])) {
            $result = $_SERVER['HOME'];
        } else {
            $result = getenv("HOME");
        }
    
        if(empty($result) && function_exists('exec')) {
            if(strncasecmp(PHP_OS, 'WIN', 3) === 0) {
                $result = exec("echo %userprofile%");
            } else {
                $result = exec("echo ~");
            }
        }
    
        return $result;
    }
    

提交回复
热议问题