如何在PHP中发起GET/POST/PUT/DELETE请求并判断请求类型?
我从来没有看到 PUT/DELETE
请求是如何发送的。
如何在 PHP 中做到这一点?
我知道如何使用curl发送GET/POST请求:
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
但是如何执行PUT
/DELETE
请求?
I never see how is PUT/DELETE
request sent.
How to do it in PHP?
I know how to send a GET/POST request with curl:
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
But how to do PUT
/DELETE
request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于
DELETE
,请使用curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
对于
PUT
使用curl_setopt($ch, CURLOPT_PUT, true);
不依赖于安装 cURL 的替代方案是使用
file_get_contents
使用自定义 HTTP 流上下文。查看这两篇关于使用 PHP 进行 REST 的文章
For
DELETE
usecurl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
For
PUT
usecurl_setopt($ch, CURLOPT_PUT, true);
An alternative that doesn't rely on cURL being installed would be to use
file_get_contents
with a custom HTTP stream context.Check out these two articles on doing REST with PHP
一般来说,如果您想发送一些“非 GET”请求,您通常会使用
您将使用
curl_setopt
函数来配置您发送的请求;在大量可能的选项中,要更改请求方法,您至少会对以下选项感兴趣:(引用):CURLOPT_CUSTOMREQUEST
:要使用的自定义请求方法执行 HTTP 请求时,而不是“GET
”或“HEAD
”。这对于执行“DELETE
”或其他更晦涩的 HTTP 请求非常有用。CURLOPT_HTTPGET
:TRUE
将 HTTP 请求方法重置为GET
。CURLOPT_POST
:TRUE
执行常规 HTTPPOST
。CURLOPT_PUT
:TRUE
到 HTTPPUT
文件。要PUT
的文件必须使用CURLOPT_INFILE
和CURLOPT_INFILESIZE
设置。当然,
curl_setopt
并不是您将使用的唯一函数;请参阅curl_exec
的文档页面如何使用curl发送请求的示例。(是的,该示例非常简单,并发送
GET
请求 - 但您应该能够从那里进行构建;-))Generally speaking, if you want to send some "non-GET" request, you'll often work with curl.
And you'll use the
curl_setopt
function to configure the request you're sending ; amongst the large amount of possible options, to change the request method, you'll be interested by at least those options (quoting) :CURLOPT_CUSTOMREQUEST
: A custom request method to use instead of "GET
" or "HEAD
" when doing a HTTP request. This is useful for doing "DELETE
" or other, more obscure HTTP requests.CURLOPT_HTTPGET
:TRUE
to reset the HTTP request method toGET
.CURLOPT_POST
:TRUE
to do a regular HTTPPOST
.CURLOPT_PUT
:TRUE
to HTTPPUT
a file. The file toPUT
must be set withCURLOPT_INFILE
andCURLOPT_INFILESIZE
.Of course,
curl_setopt
is not the only function you'll use ; see the documentation page ofcurl_exec
for an example of how to send a request with curl.(Yes, that example is pretty simple, and sends a
GET
request -- but you should be able to build from there ;-) )