首页 > 解决方案 > How write PHP code for Curl - X Post commands

问题描述

I needs to implement below curl command in PHP. curl -X POST "http://XXXXXXXXX/api/service" -F "scenario=http://XXXXXXXXX/api/service/scenarios/3728940075"

For this i have written below code but its throwing 400 bad request. Please help me

$postdata = array("scenario" => "http://XXXXXXXXX/api/service/scenarios/3728940075" );


echo "  --- cURL postdata #:" . $postdata;
$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, false);
curl_setopt($curl,CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_URL, "http://XXXXXXXXX/api/service");
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 
//curl_setopt($curl,CURLOPT_POST, count($postdata));
curl_setopt($curl,CURLOPT_POSTFIELDS, $postdata);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
//curl_setopt($curl, CURLOPT_FAILONERROR, true); 

$response = curl_exec($curl);
echo " --- cURL response #:" . $response;
$err = curl_error($curl);
echo " --- cURL Error #:" . $err;
curl_close($curl);
if ($err) {
    echo "<h2> Error found in setting up trigger. Please contact the Start Administrator</h2>";
    echo "cURL Error #:" . $err;
} else {
    echo " ----   setupTrigger -------".$response;
    return $response;
}

Please help me to resolve this issue

标签: php

解决方案


我已经检查了您的 php curl 代码和 curl -F 命令行发送的确切请求标头和发布数据。唯一的区别是 curl -F 命令行添加 User-Agent 头,而 php curl 默认不包含任何 User-Agent。

远程服务器可能会检查 UA 字符串,如果为空则返回 400 错误请求。

尝试添加类似的内容:

curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0');

到你的 php curl 代码。


推荐阅读