Get IP address from ifconfig using PHP

2019-05-31 10:22发布

问题:

I have the next php code:

<?php
   $ip = shell_exec("/sbin/ifconfig  | grep 'inet:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'");
   echo $ip;
?>

It works fine when I run it from the command line ($php5 ip.php), but when I run it from my browser it shows nothing (http://localhost/ip.php).

By the way, I'm trying to print my IP address but whenever I use $_SERVER['SERVER_ADDR']; I get 127.0.0.1.

回答1:

It will work without colon next to 'inet'

grep 'inet '


回答2:

I would write a bash script to do that and execute the bash script. The CLI version of PHP has access to your PATH environment variable, which the Apache module might not have access to.

#!/bin/bash

/sbin/ifconfig | grep 'inet:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'

then:

<?php

$ip = shell_exec('/path/to/shell/script');
print $ip;

?>


标签: php ip ifconfig