2

我购买 GeoIP Web Services 以从那里获取客户国家/地区的 IP 用于我的数据库,他们给了我一个 php 代码以从那里获取 API 的响应,以告诉我来自哪个 IP 的女巫国家,这是他们给我的代码:

    $query = "http://geoip.maxmind.com/f?l=" . $license_key . "&i=" . $ipaddress;
$url = parse_url($query);
$host = $url["host"];
$path = $url["path"] . "?" . $url["query"];
$timeout = 1;
$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
        or die('Can not open connection to server.');
if ($fp) {
  fputs ($fp, "GET $path HTTP/1.0\nHost: " . $host . "\n\n");
  while (!feof($fp)) {
    $buf .= fgets($fp, 128);
  }
  $lines = explode("\n", $buf);
  $data = $lines[count($lines)-1];
  fclose($fp);
} else {
  # enter error handing code here
}
echo $data;

我得到 $data 值,它告诉我 $ipaddress 来自哪里......但我得到一个错误:未定义的变量 $buf ?

4

2 回答 2

2

添加

$buf = '';

在您的代码之上

于 2013-01-23T22:12:30.490 回答
1

将您的代码更改为:

$query = "http://geoip.maxmind.com/f?l=" . $license_key . "&i=" . $ipaddress;
$url = parse_url($query);
$host = $url["host"];
$path = $url["path"] . "?" . $url["query"];
$timeout = 1;
$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
        or die('Can not open connection to server.');

if ($fp) {
  fputs ($fp, "GET $path HTTP/1.0\nHost: " . $host . "\n\n");
  $buf = ''; //This is the line of code that initializes $buf and will keep the undefined error from happening 
 while (!feof($fp)) {
    $buf .= fgets($fp, 128);
  }
  $lines = explode("\n", $buf);
  $data = $lines[count($lines)-1];
  fclose($fp);
} else {
  # enter error handing code here
}
echo $data;
于 2013-01-23T22:13:56.020 回答