Search code examples
phpcommand-lineenvironmentipconfig

Identification environment in PHP when script run with CLI


I'am using apropriate config for each environment. In order to acomplissh that i have to identify with 'HTTP_HOST' variable , for example:

if($_SERVER['HTTP_HOST']=='example.com'){

the problem is that when i run the code from cli , locally i can't figure out what is the environment.

i found some code that solve my problem

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'){

But ifconfig works only in linux , i identify which OS and change 'ifconfig' to 'ipconfig'(windows ) using:

$getIpFunc = PHP_OS=='Linux'?`ifconfig`:`ipconfig`;
preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', $getIpFunc, $ips);

but i don't receive the ip in windows


Solution

  • You could use getHostByName in both environments. It would probably be more reliable than using ipconfig or ifconfig.

    $localIP = getHostByName(getHostName());
    

    http://php.net/manual/en/function.gethostbyname.php http://php.net/manual/en/function.gethostname.php