Print php array

2

Good afternoon everyone! : D I am creating a page in php that informs me of my local ip, I am doing this through the command: shell_exec('ipconfig') until then it is fine as it returns the ip of my correct machine, however it does not return only the ip , but also Address Ipv6 , Ipv4 , subnet mask, Gateway ... finally returns the whole class there as when typing the command ipconfig in the PC Command Prompt.

Here's my dilemma! I want it to print on the screen just the Ip , but it is printing a list and in the middle of this list is my ip. So the bright mind here thought it could print only the ip if the list was an array, assigns the value returned by the command to an array variable and printed the variable and the obvious happened, it printed:

  Array ( [0] => a turminha toda do resultado do comando ipconfig e blá blá blá ) 

My entire list is index 0. I wanted to know if there is a way to split the array, to print only the ip or if there is another way to print only the ip of this list.

Thank you, if anyone knows I am very grateful :)

There goes the code:

<!DOCTYPE html>
<html>
<head>
    <title>teste</title>
    <META HTTP-EQUIV="Refresh" CONTENT="60">
</head>
<body>
<?php 
$str = array(shell_exec('ipconfig'));

print_r($str);
?>
</body>
</html> 
    
asked by anonymous 27.07.2016 / 20:58

1 answer

3

You can use exec for this purpose, instead of shell_exec .

$exec = exec('ipconfig', $array);

if($exec){

echo '<pre>';
var_dump($array);
echo '</pre>';

}

Will return:

array(15) {
  [0]=>
  string(0) ""
  [1]=>
  string(29) "Configuração de IP do Windows"
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  [4]=>
  string(43) "Adaptador de Rede sem Fio Conexão Local* 2:"
  [5]=>
  string(0) ""
  [6]=>
  string(67) "   Estado da mídia. . . . . . . . . . . . . .  : mídia desconectada"
  [7]=>
  string(48) "   Sufixo DNS específico de conexão. . . . . . :"
  [8]=>
  string(0) ""
  [9]=>
  string(32) "Adaptador de Rede sem Fio Wi-Fi:"
  [10]=>
  string(0) ""
  [11]=>
  string(48) "   Sufixo DNS específico de conexão. . . . . . :"
  [12]=>
  string(60) "   Endereço IPv4. . . . . . . .  . . . . . . . : 192.AAA.AAA.AAA"
  [13]=>
  string(62) "   Máscara de Sub-rede . . . . . . . . . . . . : 255.255.255.0"
  [14]=>
  string(60) "   Gateway Padrão. . . . . . . . . . . . . . . : 192.BBB.BBB.BBB"
}

To get IPv4, just use this:

  

/! \ This is a gambiarra!

foreach($array as $item){

    if (!!strpos($item, 'IPv4')) {
        list($descricao, $ip) = explode(': ', $item);
    }

}

echo $ip;

Result:

192.AAA.AAA.AAA

Another solution:

If you just want to get the IP address of the server, you can use two changes.

Get "IPv4 Address":

$nomeHost = gethostname();
$ip = gethostbyname($nomeHost);

echo $ip;

Result:

192.AAA.AAA.AAA

Get the "Server Address":

$ip = $_SERVER['SERVER_ADDR'];

echo $ip;

Result:

127.0.0.1
    
27.07.2016 / 21:13