Get IP address from ifconfig using PHP

时光毁灭记忆、已成空白 提交于 2019-12-23 03:21:36

问题


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;

?>


来源:https://stackoverflow.com/questions/13379922/get-ip-address-from-ifconfig-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!