【问题标题】:Sending DELETE to API using PHP使用 PHP 向 API 发送 DELETE
【发布时间】:2015-08-13 00:54:06
【问题描述】:

我对在 API 包装器之外使用 API 很陌生。我可以使用

访问 API
curl -u username:password https://company.c
om/api/v1/resources/xxxxxxx

这会加载所有信息,但我需要做的是根据文件名数组向 url 发送 DELETE;例如['/js/jquery.js']。参数名称为 Files。

我已经在代码中包含了目录和文件名变量。

$storageFilename = $directoryname . "/" . $asset->name;

上面返回数据库中的 /directoryname/filename。

【问题讨论】:

标签: php json api curl


【解决方案1】:

使用 PHP 中的 cURL 库发送 HTTP(S) DELETE:

$url = 'https://url_for_your_api';

//this is the data you will send with the DELETE
$fields = array(
    'field1' => urlencode('data for field1'),
    'field2' => urlencode('data for field2'),
    'field3' => urlencode('data for field3')
);

/*ready the data in HTTP request format
 *(like the querystring in an HTTP GET, after the '?') */
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

/*if you need to do basic authentication use these lines,
 *otherwise comment them out (like, if your authenticate to your API
 *by sending information in the $fields, above. */
 $username = 'your_username';
 $password = 'your_password';
 curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
/*end authentication*/

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

/*unless you have installed root CAs you can't verify the remote server's
 *certificate.  Disable checking if this is suitable for your application*/
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//perform the HTTP DELETE
$result = curl_exec($ch);

//close connection
curl_close($ch);

/* this answer builds on David Walsh's very good HTTP POST example at:
 * http://davidwalsh.name/curl-post 
 * modified here to make it work for HTTPS and DELETE and Authentication */

【讨论】:

  • 好点。我编辑了答案以包括使用基本身份验证的 API 的登录。 (有些您将身份验证信息作为字段传递。对于这些类型的 API,只需注释掉基本身份验证行。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
相关资源
最近更新 更多