【问题标题】:Geo location only working on localhost地理位置仅适用于本地主机
【发布时间】:2015-07-06 18:06:31
【问题描述】:

我已经在本地主机上成功地在我的网站中实现了地理位置。但是,将网站上传到在线服务器后,它就不再起作用了。我得到一个 bool(false) 错误。

Geo.php

<?php 

      class Geo{

      protected $api = 'http://www.telize.com/geoip/%s';

      protected $properties = [];


      public function __get($key){

      if (isset($this->properties[$key])){
       return $this->properties[$key];
        }
      return null;
         }


      public function request($ip){

        $url = sprintf($this->api, $ip);
        $data = $this->sendRequest($url);
        $this->properties = json_decode($data, true);
            }

       protected function sendRequest($url){
       $curl = curl_init();
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($curl, CURLOPT_URL, $url);
       return curl_exec($curl);
          }

              }
                 ?>

index.php

<?php
  include ("functions/functions.php");

  $ip = getIp();

  require 'Geo.php';
  $geo = new Geo;
  $geo->request('$ip');
  $location = $geo->city . ',&nbsp' .$geo->region;

  ?>

getIp() 函数位于我包含的 function.php 文件中,它工作正常,因此我将其排除在外。

【问题讨论】:

  • 你在哪一行得到错误?
  • @jcuenod,它只是回显:bool(false),没有说什么行。
  • 请注意,$geo-&gt;request('$ip'); 将传递字符串 $ip 而不是该变量的值。请改用$geo-&gt;request($ip);
  • @Stefan,还是不行
  • 有更好的方法吗?

标签: php jquery html geolocation


【解决方案1】:

代码改进。

地理.php

<?php 

class Geo {

    protected $api = 'http://www.telize.com/geoip/%s';
    protected $properties = [];

     public function __get($key)
     {
         if (isset($this->properties[$key]))
             return $this->properties[$key];

         return null;
      }

      public function request($ip) {
          $url = sprintf($this->api, $ip);
          $data = $this->sendRequest($url);
          if($data !== false) $this->properties = json_decode($data, true);
          return ($data !== false);
      }

       protected function sendRequest($url) {
           $curl = curl_init();
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
           curl_setopt($curl, CURLOPT_URL, $url);
           return curl_exec($curl);
       }

}
?>

index.php

<?php
  include ("functions/functions.php");

  $ip = getIp();

  require 'Geo.php';
  $geo = new Geo;
  if($geo->request($ip)) {
      $location = $geo->city . ',&nbsp' .$geo->region;
  }
  else {
    // Location not found
  }

?>

【讨论】:

  • 感谢您的改进。我找不到位置,所以我猜它无法请求 IP 地址,并且我确定 IP 地址在那里,因为我已经回显了变量 $ip 并且它是正确的。
  • 还是什么都没有。可以建议我可以用来获取用户位置的另一种方法吗?
  • @chris94 因为您的 getIp 函数在本地服务器/网络之外无法工作。
猜你喜欢
  • 2018-11-16
  • 2017-02-25
  • 2023-04-05
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 2012-10-08
相关资源
最近更新 更多