curl cross origin请求需要用户代理才能工作?

时间:2017-06-15 15:28:51

标签: php curl request cors

我在尝试查询我的跨域API时遇到了麻烦。

这是一个简单的例子:

curl -i -X POST https://example.com/api/v1/log/create -d 'value=fesfse' -d 'type=3'

HTTP/1.1 403 Forbidden
Date: Thu, 15 Jun 2017 15:07:24 GMT
Content-Type: text/html; charset=iso-8859-1
Content-Length: 219
Set-Cookie: SERVERID31396=234083; path=/; max-age=900
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Max-Age: 0
Access-Control-Allow-Headers: *
Vary: Accept-Encoding
X-IPLB-Instance: 9386

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /api/v1/log/create
on this server.</p>
</body></html>

但添加User-Agent的同一个请求正在运行(无论价值是多少)!

curl -i -X POST https://example.com/api/v1/log/create -d 'value=fesfse' -d 'type=3' -H 'User-Agent: toto'

HTTP/1.1 200 OK
Date: Thu, 15 Jun 2017 15:09:27 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Set-Cookie: SERVERID31396=234083; path=/; max-age=900
Server: Apache
X-Powered-By: PHP/7.0.15
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
Access-Control-Max-Age: 0
X-IPLB-Instance: 9387

{"status_code":200,"message":null,"data":null}

它是ovh.com上的共享托管服务器,在Apache 2上运行php 7.0.15 谁能解释这种行为?

2 个答案:

答案 0 :(得分:2)

Curl有一个内置的用户代理字符串,如User-Agent: curl/7.51.0,如果您没有指定,则使用它。找到拒绝来自它的请求的服务器并不罕见。 (这很愚蠢,因为它很容易伪造。)如果主持人像这样挑剔,你可以提供一个user agent string from a real browser来欺骗主人。

答案 1 :(得分:1)

您正在请求查看User-Agent标头并拒绝某些请求的服务器上的代码。大概是因为它们不是它所信任的浏览器或机器人。