地理位置仅适用于localhost

时间:2015-07-06 18:06:32

标签: php jquery html html5 geolocation

我已经在localhost上成功实现了我的网站的地理位置。然而,在将网站上传到在线服务器时,它不再起作用。我收到 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文件中,工作正常,因此我将其排除在外。

1 个答案:

答案 0 :(得分:0)

代码改进。

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);
          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
  }

?>
相关问题