How do I find my server's IP address in PHP(CLI)

Viewed 62618

Aside from the obvious (localhost, 127.0.0.1) does PHP (command line interface!) have a mechanism for discovering the IP of the computer the script is running on?

$_SERVER[*] will not work as this is not a Web app - this is a command line script.

TIA

7 Answers

If you want to find local ip v4 and not WSL address.

Thanks https://stackoverflow.com/users/272555/impressthenet-web-developer for the https://stackoverflow.com/a/6256719/15610724
I rewrote the code for Windows 10 and php 7.4:

function getServerAddrAndName() {
  $serverName = getHostName();
  $addr = 'unknown';

  if (stristr(PHP_OS, 'WIN')) {
    // WIN 10 checked
    $lines = [];
    exec('ipconfig', $lines);
    // print_r($lines);
    $inWsl = FALSE;
    foreach($lines as $i => $line) {
      if ($line && stripos($line, '  ') !== 0) {
        // header-information
        $inWsl = stripos($line, '(WSL)');
        continue;
      }
      if (!$line || $inWsl) {
        // information is null or from WSL connect
        continue;
      }
      if ((stripos($line,'IP Address') || stripos($line, 'IPv4 Address')) && stripos($line,':')) {
        [, $ip] = explode(':', $line);
        $matches = [];
        $reg = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/';
        if (preg_match($reg, $ip, $matches)) {
          [$ip] = $matches;
          if (filter_var($ip, FILTER_VALIDATE_IP)) {
            $addr = $ip;
            break;
          }
        }
      }
    }
  } else {
    // Ubuntu 20.04 checked
    $addr = shell_exec("ip addr show eth0 | grep \"inet\b\" | awk '{print $2}' | cut -d/ -f1");
  }

  return ['serverAddr' => $addr, 'serverName' => $serverName];
}
Related