简体   繁体   中英

What is wrong with this PHP cURL request to a Google API?

EDIT/UPDATE: 1) I tried the URL with just http (not https), and it worked in my browser. But, it did not work with PHP and cURL!

2) I read the curl error message, and it said Couldn't resolve host 'ajax.googleapis.com' . But, again, it could resolve the host from my web browser on the same machine!

3) Google explicitly stated that I needed the CURLOPT_REFERER to be set, so I'm keeping it.

Any other ideas? Thanks!

ORIGINAL POST:

When I enter this URL into my web browser, I get the JSON response I want. But, when I run the following cURL code in PHP5 (via Apache 2), the request fails. Can anyone point to some possible problems?

$url = "https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hola&langpair=es%7Cen&key=I-REMOVED-MY-API-KEY-FOR-STACKOVERFLOW-POST";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_REFERER, "http://my.ip.addr.ess/");
$response = curl_exec($ch);
var_dump($response);

The output is bool(false);

I have no idea what's wrong... do you? Thanks!

When the response if false, there was an error. Check for errors doing something like this:

if (($response = curl_exec($ch)) === FALSE) {
    echo curl_error($ch);
    exit();
}

In production code you definitely want to do something else on an error condition (instead of outputting the error message and exiting), but this will help you for debugging.

Probably because you're accessing a HTTPS resource.

Quick fix: curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Use http:// instead of https:// . Code works fine without the key in the query string. CURLOPT_REFERER is also not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM