我尝试使用geoplugin来获取PHP中的用户gelocation和城市。
但是,当我运行此代码时,我收到以下错误:
Notice: unserialize(): Error at offset 0 of 172 bytes in ndex.php on line 21
这是我的全部代码:
$user_ip = getenv('REMOTE_ADDR');
echo $user_ip;
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=".$user_ip.""));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$country = $geo["geoplugin_countryName"];
echo "City: ".$city."<br>";
echo "Region: ".$region."<br>";
echo "Country: ".$country."<br>";
并且错误中显示的第21行是:
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=".$user_ip.""));
我在其他服务器上使用过此代码并且工作得很好但是在新服务器上我得到了那个我不知道为什么会出错的错误。
有人可以就此问题提出建议吗?
任何帮助将不胜感激。
编辑:
我将我的代码编辑为以下内容并仍然得到相同的错误:
$user_ip = getenv('REMOTE_ADDR');
$geo = file_get_contents("http://www.geoplugin.net/php.gp?ip=".$user_ip."");
$string = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $geo);
$geo = unserialize($string);
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$country = $geo["geoplugin_countryName"];
echo "City: ".$city."<br>";
echo "Region: ".$region."<br>";
echo "Country: ".$country."<br>";
答案 0 :(得分:1)
该URL的输出似乎没有正确序列化,至少对于基于英国的IP地址 - 我通过手动转到URL进行了测试:
http://www.geoplugin.net/php.gp?ip=81.201.130.8
给出了:
a:18:{s:17:"geoplugin_request";s:12:"81.201.130.8";s:16:"geoplugin_status";i:206;s:16:"geoplugin_credit";s:145:"Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\'http://www.maxmind.com\'>http://www.maxmind.com</a>.";s:14:"geoplugin_city";s:0:"";s:16:"geoplugin_region";s:0:"";s:18:"geoplugin_areaCode";s:1:"0";s:17:"geoplugin_dmaCode";s:1:"0";s:21:"geoplugin_countryCode";s:2:"GB";s:21:"geoplugin_countryName";s:14:"United Kingdom";s:23:"geoplugin_continentCode";s:2:"EU";s:18:"geoplugin_latitude";s:4:"51.5";s:19:"geoplugin_longitude";s:5:"-0.13";s:20:"geoplugin_regionCode";s:0:"";s:20:"geoplugin_regionName";N;s:22:"geoplugin_currencyCode";s:3:"GBP";s:24:"geoplugin_currencySymbol";s:6:"£";s:29:"geoplugin_currencySymbol_UTF8";s:2:"£";s:27:"geoplugin_currencyConverter";s:6:"0.6834";}
将其粘贴到在线反序列化程序(例如http://blog.tanist.co.uk/files/unserialize/)中确认它不起作用 - 我认为这是因为它将英镑符号视为2个字符(因为它是UTF-8) - 如果我替换s:2: “£”与s:1:“£”它正确地反序列化。