使用PHP将DELETE发送到API

时间:2015-05-30 02:54:25

标签: php json api curl

我在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;

Above返回数据库中的/ directoryname / filename。

1 个答案:

答案 0 :(得分:0)

使用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 */