PHP curl 失败,而命令行 curl 工作


php curl fails whereas command line curl works

我正在尝试使用以下 curl 使用 php 从谷歌地图获取一些数据

    curl_setopt($ch,CURLOPT_URL, trim($_url));
    curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.35.0");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POST, 0);
    $output=curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

但是,这从谷歌地图 API 返回以下内容:标准类对象( [error_message] => 此 API 项目无权使用此 API。请确保在 API 控制台中激活此 API:了解更多:https://code.google.com/apis/console [结果] => 数组 ( )

[status] => REQUEST_DENIED
)

当我尝试通过命令行 curl 使用相同的 url 时,它可以工作。

curl -v https://maps.googleapis.com/maps/api/geocode/jsonaddress=Salt+Lake+City%2CUT&key=AIasasasasaasasg

我在 PHP 标头中看到以下内容:

> GET /maps/api/geocode/json?address=Salt+Lake+City%2CUT&key=AIasasasasassahg HTTP/1.1
 User-Agent: curl/7.35.0
 Host: maps.googleapis.com
Accept: */*

< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Date: Sat, 06 Dec 2014 14:14:13 GMT
< Pragma: no-cache
< Expires: Fri, 01 Jan 1990 00:00:00 GMT
< Cache-Control: no-cache, must-revalidate
< Vary: Accept-Language
< Access-Control-Allow-Origin: *
* Server mafe is not blacklisted
< Server: mafe
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Alternate-Protocol: 443:quic,p=0.02
< Transfer-Encoding: chunked
< 
* Connection #0 to host maps.googleapis.com left intact

而卷曲标题看起来像

CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using ECDHE-RSA-AES128-GCM-SHA256
* Server certificate:
*    subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=*.googleapis.com
*    start date: 2014-11-20 09:42:23 GMT
*    expire date: 2015-02-18 00:00:00 GMT
*    subjectAltName: maps.googleapis.com matched
*    issuer: C=US; O=Google Inc; CN=Google Internet Authority G2
*    SSL certificate verify ok.
> GET /maps/api/geocode/json?address=Salt+Lake+City%2CUT HTTP/1.1
> User-Agent: curl/7.35.0

基本上GET是不同的。我能做些什么来做到这一点吗?我已经将 API 设置为从任何引用者接受。是

我有很多(令人沮丧的)小时都遇到了同样的问题。您必须将分隔参数的"&"替换为 &amp;

我不知道它实际上适用于 CLI curl(和任何浏览器)的原因:如果没有字符转义,"key"参数似乎根本没有发送,但它使谷歌地图 api 返回请求的数据,就像一切都很好......

bad:  GET /maps/api/geocode/json?address=Salt+Lake+City%2CUT  
good: GET /maps/api/geocode/json?address=Salt+Lake+City%2CUT&key=AIasasasasassahg

显然,您的URL中缺少关键参数。

curl_setopt($ch,CURLOPT_URL, trim($_url));

从这段代码来看,问题所在一定是一个糟糕$_url