Problems getting updated information with PHP exec()

Viewed 35

I have simple code that uses exec() to set a variable with some system information (like current IP.) I execute the code and display the information. I change the IP address of the computer and rerun the code. I'm using unset() to clear the variable before executing the code, however, it still displays the old information. How do I obtain the current information using exec()? Thanks in advance and sorry for the noob-iness.

  <button type="button" class="btn btn-info btn-lg" onclick="showip()">Get IP</button>

  <script>
  function showip(){
     <?php
        unset($return);
        unset($ip);
        exec('wget https://ipinfo.io/ip -qO -', $return);
        $ip = $return[0];
     ?>
     curip = <?php echo(json_encode($ip, JSON_HEX_TAG)); ?>;
     alert("The current IP is "+curip);
   }
  </script>
2 Answers

PHP runs on the server, this is why you're always getting the same IP address.

If you want the client's IP address you can use

$_SERVER["REMOTE_ADDR"]

'REMOTE_ADDR'

The IP address from which the user is viewing the current page.

Another solution would be to make an AJAX request to https://ipinfo.io/ip.

function showip() {
    fetch("https://ipinfo.io/ip")
    .then(function(response) {
        return response.text()
    })
    .then(function(ip) {
        alert("The current IP is " + ip)
    })
}

A server may have multiple IP addresses, including at least the public IP and the local(VPN) IP. I guess the question for obtain public IP has been answered. If you want to obtain the local IP(inside the VPN) of the server. You may try use 'ip addr' like this:

function ips(){
  $ips = [];
  exec('ip addr', $lines);
  foreach($lines as $line){
    $fields = explode(" ",trim($line));
    if($fields[0] == 'inet'){
      $ip = explode("/",$fields[1])[0];
      $ifname = $fields[count($fields)-1];
      $ips[$ifname] = $ip;
    }
  }
  return $ips;
}

This will return all local IP(v4) of each interfaces. If you want to have IPv6, just change 'inet' to 'inet6'.

Related