1

我有下一个php代码:

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

当我从命令行 ( $php5 ip.php) 运行它时它工作正常,但是当我从浏览器运行它时它什么也不显示 ( http://localhost/ip.php)。

顺便说一句,我正在尝试打印我的 IP 地址,但每当我使用时,$_SERVER['SERVER_ADDR'];我都会得到127.0.0.1.

4

2 回答 2

4

它可以在“inet”旁边没有冒号的情况下工作

grep 'inet '
于 2012-11-14T13:45:48.110 回答
1

我会编写一个 bash 脚本来执行此操作并执行 bash 脚本。PHP 的 CLI 版本可以访问您的 PATH 环境变量,而 Apache 模块可能无法访问该变量。

#!/bin/bash

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

然后:

<?php

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

?>
于 2012-11-14T13:46:44.177 回答