Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP未定义变量?_Php_Variables - Fatal编程技术网

PHP未定义变量?

PHP未定义变量?,php,variables,Php,Variables,我购买GeoIP Web服务是为了从那里获取客户国的数据库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["qu

我购买GeoIP Web服务是为了从那里获取客户国的数据库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?

Add

$buf = '';
在代码上方

将代码更改为:

$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;

关于这条信息,到底有什么不清楚的地方PIs$buf已初始化?我不认为可以连接一个未定义的变量来初始化它。