2013-01-23 36 views
1

我買的GeoIP的Web服務,以獲得從那裏IP的客戶端國家對我的數據庫,他們給了我一個PHP代碼從那裏API響應告訴我,女巫的國家,IP而來,這裏是他們把它給我的代碼:PHP Undefind變量?

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

我得到告訴我的$數據值,其中從$ ip地址......但我得到一個錯誤:Undefind變量$ BUF ???

所以PLZ如果有任何人能幫助我嗎?

+0

到底是不清楚的信息是什麼? :P – PeeHaa

+0

是否初始化$ buf?我不認爲你可以連接一個未定義的變量來初始化它。 – joe42

回答

1

添加

$buf = ''; 

您的代碼

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;