php curl d,PHP curl_setopt等效于curl -d

博客作者分享了解决PHP中使用CURL发送PUT请求时,JSON数据未正确发送的问题。修正方法在于正确设置CURL选项,将`CURLOPT_CUSTOMREQUEST`设为'PUT'而非'POST'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我得到以下curl命令在Linux上工作:

curl -H "Content-Type:application/json" -H "Accept:application/json" -H "Authorization: Basic dGVsZXVuZzpuYWcweWEyMw==" -X PUT -d '{"requireJiraIssue": true, "requireMatchingAuthorEmail": "true"}' http://stash/rest/api/1.0/projects/TSD/repos/git-flow-release-test/settings/hooks/com.isroot.stash.plugin.yacc%3AyaccHook/enabled

但是,当我尝试在PHP上执行此操作时,数据没有正确发送到服务器,这是我的set_opt命令:

$myURL = "http://stash/rest/api/1.0/projects/TSD/repos/git-flow-release-test/settings/hooks/com.isroot.stash.plugin.yacc:yaccHook/enabled";

$hookdata_yacc = array(

'requireJiraIssue' => true,

'requireMatchingAuthorEmail' => true

);

$data = json_encode($hookdata_yacc);

$headers = array(

"Content-Type: application/json",

"Accept: application/json",

"Authorization: Basic dGVmyPasswordEyMw==",

"Content-Length: " . strlen($data)

);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $myURL);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_PUT, 1);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

return (curl_exec($curl));

我错过了什么?

解决方法:

您使用了不正确的CURL选项. CURLOPT_PUT用于发送文件,不适合您的情况.您必须使用CURLOPT_CUSTOMREQUEST选项并将其设置为“ PUT”,而不是“ POST”.

因此,代码应如下所示:

$myURL = "http://stash/rest/api/1.0/projects/TSD/repos/git-flow-release-test/settings/hooks/com.isroot.stash.plugin.yacc:yaccHook/enabled";

$hookdata_yacc = array(

'requireJiraIssue' => true,

'requireMatchingAuthorEmail' => true

);

$data = json_encode($hookdata_yacc);

$headers = array(

"Content-Type: application/json",

"Accept: application/json",

"Authorization: Basic dGVmyPasswordEyMw==",

"Content-Length: " . strlen($data)

);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $myURL);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

return (curl_exec($curl));

标签:php,curl

来源: https://codeday.me/bug/20191011/1896101.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值