2017-08-12 75 views
-1

我想實現一個服務,獲取提供的地址的GPS座標,所以我想出了以下,這在當地工作正常。然而,當我試圖在託管服務提供商上實現它時,突然間該功能失敗了,因爲沒有從Google返回結果 - 甚至沒有空白數組,甚至沒有任何結果。谷歌地理編碼返回在遠程服務器上的空白字符串 - 在本地正常工作

我認爲這是通過網絡主機封鎖,但我不知道什麼,甚至尋找。

功能:

function getCoordinates($Address, $APIKey) { 
$BaseURL = "https://maps.googleapis.com/maps/api/geocode/json?key=".$APIKey."&address="; 
$data = @file_get_contents($BaseURL.str_ireplace(" ","+",$Address)); 
//echo "Data:".$data."<br>"; 
$jsondata = json_decode($data,true); 

//echo "<pre>"; 
//print_r($jsondata); 
//echo "</pre>"; 
switch($jsondata["status"]) { 
    case "OK" : 
     if (count($jsondata["results"]) > 1) { 
      return array("status" => "FAIL", "message" => "Multiple results were returned"); 
     } 
     else { 
      if (isset($jsondata["results"][0]["geometry"]["location"])) { 
       return array("status" => "SUCCESS","latitude" => $jsondata["results"][0]["geometry"]["location"]["lat"],"longitude" => $jsondata["results"][0]["geometry"]["location"]["lng"]); 
      } 
     } 
     return $jsondata["results"]; 
     break; 
    case "ZERO_RESULTS" : 
     return array("status" => "FAIL", "message" => "Zero Results were returned"); 
     break; 
    case "OVER_QUERY_LIMIT" : 
     return array("status" => "FAIL", "message" => "API Key is over the daily limit. It will automatically try again tomorrow"); 
     break; 
    case "REQUEST_DENIED" : 
     return array("status" => "FAIL", "message" => "Request was denied"); 
     break; 
    case "INVALID_REQUEST" : 
     return array("status" => "FAIL", "message" => "Invalid request, typically because the address is missing"); 
     break; 
    case "UNKNOWN_ERROR" : 
     return array("status" => "FAIL", "message" => "Unknown error, Request could not be processed due to a Google server error. It may work again if you try later."); 
     break; 
    case "ERROR" : 
     return array("status" => "FAIL", "message" => "Error, the request timed out"); 
     break; 
    default: 
     $Message = array("Failure",print_r($jsondata)); 
     return array("status" => "FAIL", "message" => $Message); 
     break; 
} 

}

經由被稱爲:

$LocationCoordinates = getCoordinates("123 Main Street, Toronto, ON", [[$MapsAPIKey]]); 

出於測試目的,我未註釋出4行接近函數的頂部和第一返回的單詞'數據'沒有任何關係。接下來的三行,預計只是返回相應的'pre'標籤。

檢查控制檯日誌,並沒有指出錯誤。我在服務器上嘗試了一個快速的客戶端腳本,它似乎工作正常。

回答

1

最終這是因爲在遠程服務器上禁用了'allow_url_fopen'設置,實際上禁用了我的函數中的'file_get_contents'部分。我可以通過主機的phpinfo頁面查看,但也可以通過how to check if allow_url_fopen is enabled or not表示爲Marcin Orlowski

我能夠通過修改函數來使用cURL來解決此問題。

我基本上是一無所知捲曲,但我換成這條線,在我的功能:

$data = file_get_contents($BaseURL.str_ireplace(" ","+",$Address)); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $BaseURL.str_ireplace(" ","+",$Address)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$data = curl_exec($ch); 

雖然它不再作品在我的本地機器上(因爲我不有cURL安裝/配置),它在遠程服務器上工作,這是最重要的。

相關問題