PHP cURL 发布请求不起作用


PHP cURL Post request not working

我在运行正确的 cURL 请求时遇到问题。我打算对 URL 发出发布请求。

该示例仅运行命令行 cURL 请求

$ curl -i -X POST {URL}

问题我正在运行以下代码,并且收到"400 错误请求"

$ch = curl_init();
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
$output = curl_exec( $ch );
curl_close( $ch );

任何人都可以帮助正确发送请求。

您缺少要通过请求获得的CURLOPT_POSTFIELDS。如此处所述,您将需要设置这些字段:

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>

试试这个:

开机自检功能:

function httpPost($url,$params)
{
  $postData = '';
   //create name value pairs seperated by &
   foreach($params as $k => $v) 
   { 
      $postData .= $k . '='.$v.'&'; 
   }
   rtrim($postData, '&');
    $ch = curl_init();  
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_POST, count($postData));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

调用函数:

$params = array(
   "name" => "Ravishanker Kusuma",
   "age" => "32",
   "location" => "India"
);
echo httpPost("http://hayageek.com/examples/php/curl-examples/post.php",$params);

看看,如果有帮助。参考:链接

curl_setopt( $ch, CURLOPT_POST, TRUE );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $array );

查看手册

要发布,只需使用以下 curl 选项并尝试。

(if your url is - "https") {
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //if required.
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
return curl_exec($ch);

我猜您正在传递的网址没有帖子字段。 你可以利用CURLOPT_POSTFIELDS和你的帖子参数,或者使用http_build_query(发布参数)将其附加到URL上http://www.url.com?arg1=val1&arg2=val2

同样在相同的代码上花费了 5 个小时后,我刚刚找到了我的问题的解决方案

如果您在 post 字段中使用数组,则必须json_encode该数组以识别为 POST 参数

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       $data = curl_exec($curl);

所以这是带有 POST 请求的工作卷曲代码给一个代表+ 如果我的