有没有人知道如何使用PHP发送“OPTIONS”请求。
我找不到这样做的curl setopt。
我正在使用php 5.6.7
我已经想出了GET,POST,DELETE和PUT。只需要OPTIONS。
我在下面尝试了高清的答案:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"theurl");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "OPTIONS");
$r = curl_exec($ch);
print_r($http_response_header);
curl_close($ch);
我收到了错误:
Undefined variable: http_response_header in C:\IIS_Emea\WebRoot\Site01\test\rest1.php on line 7
如何获得结果?
答案 0 :(得分:6)
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://stackoverflow.com/',
CURLOPT_CUSTOMREQUEST => 'OPTIONS',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_VERBOSE => true,
));
$r = curl_exec($ch);
echo PHP_EOL.'Response Headers:'.PHP_EOL;
print_r($r);
curl_close($ch);
它的作用:
CURLOPT_CUSTOMREQUEST => 'OPTIONS'
- 定义HTTP请求方法。CURLOPT_RETURNTRANSFER => true
- 告诉curl_exec
不输出结果但返回结果。CURLOPT_HEADER => true
- 返回标题。CURLOPT_NOBODY => true
- 不要回归身体。CURLOPT_VERBOSE => true
- 仅用于调试,在生产时将其删除。它允许查看库完成的请求和收到的响应。脚本的输出如下所示
* Trying 104.16.36.249...
* Connected to stackoverflow.com (104.16.36.249) port 80 (#0)
> OPTIONS / HTTP/1.1
Host: stackoverflow.com
Accept: */*
< HTTP/1.1 200 OK
< Date: Wed, 20 Apr 2016 09:02:44 GMT
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Set-Cookie: __cfduid=d96e454843a81721eeb77cc4ebb49d2c91461142964; expires=Thu, 20-Apr-17 09:02:44 GMT; path=/; domain=.stackoverflow.com; HttpOnly
< Cache-Control: public, no-cache="Set-Cookie", max-age=60
< Expires: Wed, 20 Apr 2016 09:03:44 GMT
< Last-Modified: Wed, 20 Apr 2016 09:02:44 GMT
< Vary: *
< X-Frame-Options: SAMEORIGIN
< X-Request-Guid: a2f90416-9ec1-4ec9-b2d9-a69e22cc05d5
< Set-Cookie: prov=37be6386-6390-40fb-9f0a-42efdfcf2d71; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
< Server: cloudflare-nginx
< CF-RAY: 29676b4517f92b21-WAW
<
* Excess found in a non pipelined read: excess = 725 url = / (zero-length body)
* Connection #0 to host stackoverflow.com left intact
Response Headers:
HTTP/1.1 200 OK
Date: Wed, 20 Apr 2016 09:02:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d96e454843a81721eeb77cc4ebb49d2c91461142964; expires=Thu, 20-Apr-17 09:02:44 GMT; path=/; domain=.stackoverflow.com; HttpOnly
Cache-Control: public, no-cache="Set-Cookie", max-age=60
Expires: Wed, 20 Apr 2016 09:03:44 GMT
Last-Modified: Wed, 20 Apr 2016 09:02:44 GMT
Vary: *
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a2f90416-9ec1-4ec9-b2d9-a69e22cc05d5
Set-Cookie: prov=37be6386-6390-40fb-9f0a-42efdfcf2d71; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
Server: cloudflare-nginx
CF-RAY: 29676b4517f92b21-WAW
您将响应标头作为字符串获取,您需要解析它。但我想这不属于问题的范围。
答案 1 :(得分:0)
您可以使用JsonPath设置自定义请求
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS'); // HTTP request is 'OPTIONS'