HTTP Request Failed - Google Maps Geocoding/HostGator - php

Help would be appreciated on this. I have a txt/xml list of physical addresses that I pass through a Google Maps geocoding script but have been running into a problem where the address spits out a null value on the coord_lat and my MySQL database rejects this. The error I receive is an HTTP request failed so I believe it is problem where the Google Maps is rejecting my connection and returning a null value which then breaks my script/database. Does anyone have any idea on how to fix this connection and/or add something to the script? I am currently using HostGator as my hosting service.
Warning: file_get_contents(http://maps.google.com/maps/geo?key=AIzaSyBmT9F_ixjLlW8oDiYVqgHqt1888&output=xml&q=xxx+here) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /includes/func.php on line 297
{"status":"Failed","data":"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'coord_lat' cannot be null"}
ErrorSyntaxError: Unexpected token
function get_lat_long($address, $zipcode) {
if(strlen($zipcode) == 4){
$zipcode = '0' . $zipcode;
//echo $zipcode . "\n";
}
$apikey = "AIzaSyBmT9F_ixjLlW8oDiYVqgHqt1888";
$geourl = "http://maps.google.com/maps/geo?key=" . $apikey . "&output=xml&q=" . urlencode($address) . "+" . urlencode($zipcode);
//echo $geourl;
//echo "<br>";
// Grab XML content using $geourl
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$xml = file_get_contents($geourl, false, $context);
$xml = simplexml_load_string($xml);
//Parse the lat and long from the XML
$Lat = $xml->results->result->locations->location->displayLatLng->latLng->lat;
//echo $Lat;
$Lng = $xml->results->result->locations->location->displayLatLng->latLng->lng;
//echo $Lng;
//Return
if($Lng && $Lat) {
return array('lat'=>$Lat,
'lng'=>$Lng
);
} else {
return false;
}
}

use google maps v3 what you are using is v2 i think and its not working anymore
$Address = urlencode($Address);
$url='http://maps.googleapis.com/maps/api/geocode/json?address=egypt&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$lat = $obj->results[0]->geometry->location->lat;
$lng = $obj->results[0]->geometry->location->lng;

Related

How to handle 500 errors from Google API

How can I handle google API errors? For example, the following script will get the screenshot from the website requested:
$api_response = file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true");
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
but if the domain doesn't exists google returns this error:
Failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
How can I handle this error and create a custom error page for that?
My project is on Laravel 8.
You could do it with an if statement
if(($api_response = #file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" . $websiteURL . "&screenshot=true")) !== false) {
//success
$result = json_decode($api_response, true);
$screenshot1 = $result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
}
else{
//do error stuff
}

GET Request with params: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

I am trying to use new features available with Steam API and I am having trouble, I think this is more of general issue than actual service related itself.
I keep getting:
failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
I am trying to send GET request with parameters using:
<?php
$url = "https://api.steampowered.com/ICSGOTournaments_730/GetTournamentItems/v1?key=".$_SESSION['steam_appid']."&event=9&steamid=".$_SESSION['steam_steamid']."&steamidkey=".$_SESSION['userAuthCode'];
$response = file_get_contents($url);
echo($response);
?>
I am 100% sure the parameters are correct I think it's something rather to do with my code than Steam itself.
When I try to use same code but different API call:
$url = "https://api.steampowered.com/ICSGOTournaments_730/GetTournamentLayout/v1?key=".$_SESSION['steam_appid']."&event=9";
That executes fine and returns data so it's something related to the other two parameters.
I am wondering is there any problem with the way I am building URL's?
Sessions file (3rd Party):
<?php
if (empty($_SESSION['steam_uptodate']) or empty($_SESSION['steam_personaname'])) {
require 'SteamConfig.php';
$url = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$steamauth['apikey']."&steamids=".$_SESSION['steamid']);
$content = json_decode($url, true);
$_SESSION['steam_appid'] = $steamauth['apikey'];
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$_SESSION['steam_communityvisibilitystate'] = $content['response']['players'][0]['communityvisibilitystate'];
$_SESSION['steam_profilestate'] = $content['response']['players'][0]['profilestate'];
$_SESSION['steam_personaname'] = $content['response']['players'][0]['personaname'];
$_SESSION['steam_lastlogoff'] = $content['response']['players'][0]['lastlogoff'];
$_SESSION['steam_profileurl'] = $content['response']['players'][0]['profileurl'];
$_SESSION['steam_avatar'] = $content['response']['players'][0]['avatar'];
$_SESSION['steam_avatarmedium'] = $content['response']['players'][0]['avatarmedium'];
$_SESSION['steam_avatarfull'] = $content['response']['players'][0]['avatarfull'];
$_SESSION['steam_personastate'] = $content['response']['players'][0]['personastate'];
if (isset($content['response']['players'][0]['realname'])) {
$_SESSION['steam_realname'] = $content['response']['players'][0]['realname'];
} else {
$_SESSION['steam_realname'] = "Real name not given";
}
$_SESSION['steam_primaryclanid'] = $content['response']['players'][0]['primaryclanid'];
$_SESSION['steam_timecreated'] = $content['response']['players'][0]['timecreated'];
$_SESSION['steam_uptodate'] = time();
include 'mysql_connection.php';
$userAuth = getAuth();
if($userAuth != false){
$_SESSION['userAuthCode'] = $userAuth;
}
else{
$_SESSION['userAuthCode'] = "Unset";
}
}
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
$steamprofile['communityvisibilitystate'] = $_SESSION['steam_communityvisibilitystate'];
$steamprofile['profilestate'] = $_SESSION['steam_profilestate'];
$steamprofile['personaname'] = $_SESSION['steam_personaname'];
$steamprofile['lastlogoff'] = $_SESSION['steam_lastlogoff'];
$steamprofile['profileurl'] = $_SESSION['steam_profileurl'];
$steamprofile['avatar'] = $_SESSION['steam_avatar'];
$steamprofile['avatarmedium'] = $_SESSION['steam_avatarmedium'];
$steamprofile['avatarfull'] = $_SESSION['steam_avatarfull'];
$steamprofile['personastate'] = $_SESSION['steam_personastate'];
$steamprofile['realname'] = $_SESSION['steam_realname'];
$steamprofile['primaryclanid'] = $_SESSION['steam_primaryclanid'];
$steamprofile['timecreated'] = $_SESSION['steam_timecreated'];
$steamprofile['uptodate'] = $_SESSION['steam_uptodate'];
?>
file_get_contents - for using https need use:
from php.net
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.

HTTP Request Failed - Google Maps

I have a question with my Google Maps API. I am using a simple geocoding script to pull a txt/xml file from my server and geocoding the addresses. I have a problem with the addresses coming back as a null value and breaking the script and my database because the coord_lat and coord_long are floats and cannot accept null values.
The error I am receiving is: Warning: file_get_contents(http://maps.google.com/maps/geo?key=AIzaSyBmT9F_ixjLlW8oDiYVqgHqt14a008kXwc&output=xml&q=131+rochestor+ave+039482) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /includes/sfupdate/func.php on line 294 {"status":"Failed","data":"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'coord_lat' cannot be null"}
ErrorSyntaxError: Unexpected token
Is this a problem with my connection with Google Maps API? I see HTTP Request failed which leads me to believe that I am being rejected and the addresses are turning back a null value because of it. Advice would be appreciated, thank you.
Sorry for posting a new answer, but here is my current geocoding script.
function get_lat_long($address, $zipcode) {
if(strlen($zipcode) == 4){
$zipcode = '0' . $zipcode;
//echo $zipcode . "\n";
}
$apikey = "IzaSyBmT9F_ixjLlW8oDiYVqgHqt14a008kXwc";
$geourl = "http://maps.google.com/maps/geo?key=" . $apikey . "&output=xml&q=" . urlencode($address) . "+" . urlencode($zipcode);
//echo $geourl;
//echo "<br>";
// Grab XML content using $geourl
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$xml = file_get_contents($geourl, false, $context);
$xml = simplexml_load_string($xml);
//Parse the lat and long from the XML
$Lat = $xml->results->result->locations->location->displayLatLng->latLng->lat;
//echo $Lat;
$Lng = $xml->results->result->locations->location->displayLatLng->latLng->lng;
//echo $Lng;
//Return
if($Lng && $Lat) {
return array('lat'=>$Lat,
'lng'=>$Lng
);
} else {
return false;
}
}

alchemyAPI for php not working

I am trying to use AlchemyAPI's php sdk. I am running the same example given on their Github page.
But when I try to run the example, I get this error message-
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\wamp\www\twitter-analysis\alchemyapi.php on line 261
What could be the reason? In alchemyapi.php, this is where the warning is occuring-
private function analyze($url, $params) {
//Insert the base URL
$url = $this->_BASE_URL . $url;
//Add the API Key and set the output mode to JSON
$url = $url . '?apikey=' . $this->_api_key . '&outputMode=json';
//Add the remaining parameters
foreach($params as $key => $value) {
$url = $url . '&' . $key . '=' . $value;
}
//Create the HTTP header
$header = array('http' => array('method' => 'POST', 'Content-type'=> 'application/x-www-form-urlencoded'));
//Fire off the HTTP Request
try {
$fp = #fopen($url, 'rb',false, stream_context_create($header));
$response = #stream_get_contents($fp);
fclose($fp);
return json_decode($response, true);
} catch (Exception $e) {
return array('status'=>'ERROR', 'statusInfo'=>'Network error');
}
}
}
fopen() returns the resource if it succeeds, and false if it didn't work. The most likely case for the fopen to not work is if the path is invalid or if you don't have access to the resource.
A similar question was asked here: https://stackoverflow.com/questions/18636680/php-warning-fclose-expects-parameter-1-to-be-resource-boolean-given
Try to test on live server.
My experience it gives error in local server where works in live server.

Google maps address and map display (exceed limit image)

I have following problem. I'm using google maps in php to get the address of latitude and longitude and a map snapshot of this location.
To obtain address I use following code:
// INITIALIZING CURL
$returnValue = NULL;
$ch = curl_init();
// SERVICE CALL
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lon."&sensor=false";
// SETTING PARAMS OF CURL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// GETTING AND RESULTING RESULT
$result_part = curl_exec($ch);
$json = json_decode($result_part, TRUE);
And I parse obtained JSON as follows:
// PARSING RESULTS FROM JSON
if (isset($json['results'])) {
foreach ($json['results'] as $result_part) {
foreach ($result_part['address_components'] as $address_component) {
$types = $address_component['types'];
// GETTING STREET
if (in_array('route', $types)) {
$addr = $address_component['long_name'];
}
// GETTING STREET NUMBER
if (in_array('street_number', $types)) {
$number = $address_component['long_name'];
}
// GETTING COUNTRY
if (in_array('country', $types)) {
$country = $address_component['long_name'];
}
// GETTING POSTAL CODE
if (in_array('postal_code', $types)) {
$postal_code = $address_component['long_name'];
}
// GETTING CITY
if (in_array('locality', $types)) {
$city = $address_component['long_name'];
}
}
}
}
It works fine but sometimes the address is not obtained. It looks like some overload of requests but I dont understand why because the site that I'm programming is not accessible yet for other people.
Other problem connected to this is the map snapshots. Here is the code:
<? echo "<a href = \"https://maps.google.com/maps?q=".$lat.",".$lon."\" target=\"_blank\">" ?>
<? echo "<img src=\"http://maps.googleapis.com/maps/api/staticmap?center=" . $lat . "," . $lon . "&zoom=16&size=200x200&markers=color:blue%7Clabel:I%7C" . $lat . "," . $lon . "&sensor=false\" alt=\"google maps\" width=\"200\" height=\"200\" /></a>" ?>
This works also fine but sometimes I obtain image like this:
I doubt that I exceeded the limit.
Any ideas ? Thank you for your answers.
As #geocodezip has suggested it could be because of not using a key.
Also as per the reverse geocoding documentation on :
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
Note: Reverse geocoding is an estimate. The geocoder will attempt to find the closest addressable location within a certain tolerance; if no match is found, the geocoder will return zero results.

Categories