如何在 PHP 中启动 GET/POST/PUT/DELETE 请求并判断请求类型?

2022-01-05 00:00:00 request php

我从来没有看到 PUT/DELETE 请求是如何发送的.

I never see how is PUT/DELETE request sent.

如何在 PHP 中实现?

How to do it in PHP?

我知道如何使用 curl 发送 GET/POST 请求:

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);

但是如何做PUT/DELETE请求?

推荐答案

对于 DELETE 使用 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
对于 PUT 使用 curl_setopt($ch, CURLOPT_PUT, true);

For DELETE use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
For PUT use curl_setopt($ch, CURLOPT_PUT, true);

不依赖于安装 cURL 的替代方法是使用 file_get_contents 和 自定义 HTTP 流上下文.

An alternative that doesn't rely on cURL being installed would be to use file_get_contents with a custom HTTP stream context.

$result = file_get_contents(
    'http://example.com/submit.php', 
    false, 
    stream_context_create(array(
        'http' => array(
            'method' => 'DELETE' 
        )
    ))
);

查看这两篇关于使用 PHP 进行 REST 的文章

Check out these two articles on doing REST with PHP

  • http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
  • http://www.gen-x-design.com/archives/making-restful-requests-in-php/

相关文章