使用 CLI 脚本 运行 时 PHP 中的识别环境
Identification environment in PHP when script run with CLI
我正在为每个环境使用适当的配置。为了完成我必须使用 'HTTP_HOST' 变量来识别,例如:
if($_SERVER['HTTP_HOST']=='example.com'){
问题是当我 运行 来自 cli 的代码时,在本地我无法弄清楚什么是环境。
我找到了一些解决我问题的代码
function getIPs($withV6 = true) {
preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
return $ips[1];
}
if($_SERVER['HTTP_HOST']=='example.com'||getIPs()[0]=='55.789.258.66'){
但 ifconfig
仅适用于 linux ,我确定哪个 OS 并将 'ifconfig' 更改为 'ipconfig'(windows ) 使用:
$getIpFunc = PHP_OS=='Linux'?`ifconfig`:`ipconfig`;
preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', $getIpFunc, $ips);
但我没有收到 windows
中的 ip
您可以在两种环境中使用 getHostByName
。它可能比使用 ipconfig 或 ifconfig 更可靠。
$localIP = getHostByName(getHostName());
http://php.net/manual/en/function.gethostbyname.php
http://php.net/manual/en/function.gethostname.php
我正在为每个环境使用适当的配置。为了完成我必须使用 'HTTP_HOST' 变量来识别,例如:
if($_SERVER['HTTP_HOST']=='example.com'){
问题是当我 运行 来自 cli 的代码时,在本地我无法弄清楚什么是环境。
我找到了一些解决我问题的代码
function getIPs($withV6 = true) {
preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
return $ips[1];
}
if($_SERVER['HTTP_HOST']=='example.com'||getIPs()[0]=='55.789.258.66'){
但 ifconfig
仅适用于 linux ,我确定哪个 OS 并将 'ifconfig' 更改为 'ipconfig'(windows ) 使用:
$getIpFunc = PHP_OS=='Linux'?`ifconfig`:`ipconfig`;
preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', $getIpFunc, $ips);
但我没有收到 windows
中的 ip您可以在两种环境中使用 getHostByName
。它可能比使用 ipconfig 或 ifconfig 更可靠。
$localIP = getHostByName(getHostName());
http://php.net/manual/en/function.gethostbyname.php http://php.net/manual/en/function.gethostname.php