如何从 PHP CLI 脚本获取主目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1894917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:12:52  来源:igfitidea点击:

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

php

提问by Andrew

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

从命令行,我可以像这样获取主目录:

~/

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

如何在我的 PHP CLI 脚本中获取主目录?

#!/usr/bin/php
<?php
echo realpath(~/);
?>

回答by Felix Kling

Use $_SERVER['HOME']

$_SERVER['HOME']



Edit:

编辑:

To make it complete, see what print_r($_SERVER)gave me, executed from the command line:

为了使其完整,请查看print_r($_SERVER)从命令行执行的内容:

Array
(
    [TERM_PROGRAM] => Apple_Terminal
    [TERM] => xterm-color
    [SHELL] => /bin/bash
    [TMPDIR] => /var/folders/Lb/LbowO2ALEX4JTK2MXxLGd++++TI/-Tmp-/
    [TERM_PROGRAM_VERSION] => 272
    [USER] => felix
    [COMMAND_MODE] => unix2003
    [__CF_USER_TEXT_ENCODING] => 0x1F5:0:0
    [PATH] =>/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/texbin:/usr/X11/bin
    [PWD] => /Users/felix/Desktop
    [LANG] => de_DE.UTF-8
    [SHLVL] => 1
    [HOME] => /Users/felix
    [LOGNAME] => felix
    [DISPLAY] => /tmp/launch-XIM6c8/:0
    [_] => ./test_php2
    [OLDPWD] => /Users/felix
    [PHP_SELF] => ./test_php2
    [SCRIPT_NAME] => ./test_php2
    [SCRIPT_FILENAME] => ./test_php2
    [PATH_TRANSLATED] => ./test_php2
    [DOCUMENT_ROOT] => 
    [REQUEST_TIME] => 1260658268
    [argv] => Array
      (
        [0] => ./test_php2
      )

    [argc] => 1
    )

I hope I don't expose relevant security information ;)

我希望我不要暴露相关的安全信息;)

Windows Compatibility

Windows 兼容性

Note that $_SERVER['HOME']is not available on Windows. Instead, the variable is split into $_SERVER['HOMEDRIVE']and $_SERVER['HOMEPATH'].

请注意,这$_SERVER['HOME']在 Windows 上不可用。相反,变量被拆分为$_SERVER['HOMEDRIVE']$_SERVER['HOMEPATH']

回答by EJ Campbell

You can fetch the value of $HOME from the environment:

您可以从环境中获取 $HOME 的值:

<?php
    $home = getenv("HOME");
?>

回答by Francisco Luz

PHP allows you to get the home dir of any of the OS users. There are 2 ways.

PHP 允许您获取任何操作系统用户的主目录。有2种方式。

Method #1:

方法#1:

First of all you gotta figure out the OS User ID and store it somewhere ( database or a config file for instance).

首先,您必须找出操作系统用户 ID 并将其存储在某处(例如数据库或配置文件)。

// 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.

只要您传递之前收集的正确目标用户 ID,任何操作系统用户都可以运行此代码位,甚至是通常的网络服务器 www-data 用户。

$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:

方法#2:

Same logic from posix_getpwuid(). Here you gotta pass the target OS username instead of their uid.

来自 posix_getpwuid() 的相同逻辑。在这里,您必须传递目标操作系统用户名而不是它们的 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

文档

回答by ya.teck

This function is taken from the Drush project.

此功能取自Drush 项目

/**
 * Return the user's home directory.
 */
function drush_server_home() {
  // Cannot use $_SERVER superglobal since that's empty during UnitUnishTestCase
  // getenv('HOME') isn't set on Windows and generates a Notice.
  $home = getenv('HOME');
  if (!empty($home)) {
    // home should never end with a trailing slash.
    $home = rtrim($home, '/');
  }
  elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
    // home on windows
    $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
    // If HOMEPATH is a root directory the path can end with a slash. Make sure
    // that doesn't happen.
    $home = rtrim($home, '\/');
  }
  return empty($home) ? NULL : $home;
}

回答by Christos Lytras

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 execfunction has to be available (some hosting companies disable that kind of functions for security reasons, but that is more unlikely to happen).

如果由于任何原因getenv('HOME')无法正常工作,或者服务器操作系统是 Windows,您可以使用exec("echo ~")exec("echo %userprofile%")来获取用户目录。当然,该exec功能必须可用(一些托管公司出于安全原因禁用此类功能,但这种情况不太可能发生)

Here is a phpfunction that will try $_SERVER, getenvand finally check if the execfunction exists and use the appropriate system command to get the user directory:

下面是一个php函数,它会尝试$_SERVERgetenv最后检查该exec函数是否存在并使用相应的系统命令获取用户目录:

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;
}

回答by Jess Planck

Depends on where you are and what you're trying to do.

取决于你在哪里以及你想要做什么。

$_SERVERis completely unreliable for a non-server script, BUT $_ENV['HOME']might be better for a standard shell script. You can always print_r( $GLOBALS )and see what your environment gives you to play with. phpinfo()also spits out plaintxt when called from a CLI script, and just good ole php -iexecuted from a shell will do the same.

$_SERVER对于非服务器脚本完全不可靠,但$_ENV['HOME']对于标准 shell 脚本可能更好。您可以随时print_r( $GLOBALS )查看您的环境让您可以玩什么。phpinfo()当从 CLI 脚本调用时也会吐出 plaintxt,php -i从 shell 执行的好 ole也会做同样的事情。

回答by dustbuster

This is the method i used in a recent project:

这是我在最近的一个项目中使用的方法:

exec('echo $HOME')

I saved it into my object by doing this:

我通过这样做将它保存到我的对象中:

$this->write_Path  = exec('echo $HOME');

But you could really save it any way you want and use it anyway you see fit.

但是你真的可以以任何你想要的方式保存它,并以你认为合适的方式使用它。

回答by iateadonut

$_SERVER['HOME'] and getenv('home') did not work for me.

$_SERVER['HOME'] 和 getenv('home') 对我不起作用。

However, on PHP 5.5+, this worked to give the home directory that the file is located in:

但是,在 PHP 5.5+ 上,这可以提供文件所在的主目录:

explode( '/', __FILE__ )[2]

回答by BlackLeadPencil

Try $_SERVER['DOCUMENT_ROOT']as your home directory.

尝试$_SERVER['DOCUMENT_ROOT']作为您的主目录。

回答by streetparade

dirname(__DIR__);