Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL not working while fetching Google API data

So, I'm trying to fetch API-data using cURL, but I get the message "fail" from the else-statement in the code below. The API call is Google geocode for fetching coordinates.

The code:

 <?php 
    require_once('../db.php');
    $api_key = "somekey";
    $sqlQuery = mysql_query("SELECT `County` FROM `table`"); 
    $ch = curl_init();


    /* Fetch county */ 
    while($rows = mysql_fetch_array($sqlQuery))  { 
        $countyArr = $rows['County']; 

        /* Call google API and save coordinates for each county */ 
        curl_setopt ($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=".$countyArr.",+CA&key=".$api_key."");
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $json= curl_exec($ch, true);
        $obj = json_decode($json);

        if ($obj->status == "OK") {
            $lat = $obj->results->location->lat;
            $lng = $obj->results->location->lng;
            echo $lat;
        } else {
            echo "fail";
        }
    }
    curl_close($ch);
?> 
  • I intended to use get_file_contents() earlier but it seems like my hosting has deactivated that function.
  • Adding allow_url_fopen = on to php.ini didn't do the trick.
  • It seems like my hosting allows cURL, so that shouldn't be the problem.
  • I've tried to manually go to the API-call and I get a webpage showing the correct JSON-data.
  • The SQL-query seems to be working fine too.

Edit:

  • I tried echoing $obj->status and $obj->results->location->lat in the else-statement, nothing showed up. So $obj seems to be NULL
like image 280
Adam Avatar asked Feb 06 '23 18:02

Adam


1 Answers

It seems it fails while verifying certificate, you could disable CA verification

To turn off certificate verification (for both peer and host verification) set the following options:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 

Example

How to disable certificate verification

$address = "Ontario,CA";
$apiKey = "";

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address; //. "&key=" . $apiKey;

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // Disable SSL verification
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);

$json = json_decode($result);
print json_encode($result, JSON_PRETTY_PRINT);
like image 70
Vadim Gremyachev Avatar answered Feb 10 '23 06:02

Vadim Gremyachev