代码之家  ›  专栏  ›  技术社区  ›  user7075468

使用CLI运行脚本时PHP中的标识环境

  •  3
  • user7075468  · 技术社区  · 7 年前

    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

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

    但我在windows中没有收到ip

    1 回复  |  直到 7 年前
        1
  •  1
  •   StefanR    7 年前

    getHostByName 在这两种环境中。它可能比使用ipconfig或ifconfig更可靠。

    $localIP = getHostByName(getHostName());
    

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

    推荐文章