【问题标题】:PHP curl PUT does not continue respectively send payload/dataPHP curl PUT 不继续分别发送有效载荷/数据
【发布时间】:2022-08-17 20:39:22
【问题描述】:

我需要将一些 json 数据放入 API 端点,该端点通过命令行 curl 按预期工作,但不是通过 php curl,我不知道为什么不这样做。

我的命令是

curl -v --insecure --request PUT --url <https://blabla/blablabla> --user \'username:password\' --header \'Content-Type: application/json\' --data \'<valid json data>\'

但它在 php 中不起作用:

  // get cURL resource
  $curl = curl_init();
  
  // set cURL options
  $curloptions = array(
    CURLOPT_PUT => true,                // set method to PUT
    CURLOPT_RETURNTRANSFER => true,         // return the transfer as a string
    CURLOPT_VERBOSE => true,                // output verbose information
    CURLOPT_SSL_VERIFYHOST => false,            // ignore self signed certificates
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_USERNAME => $config[\'uag\'][\'user\'],     // set username
    CURLOPT_PASSWORD => $config[\'uag\'][\'pass\'],     // set password
    CURLOPT_HTTPHEADER => array(            // set headers
      \"Content-Type: application/json\",
    ),
    CURLOPT_POSTFIELDS => $jsondata         // set data to post / put
    );
  curl_setopt_array($curl, $curloptions);

  foreach($serverurilist as $uri) {
    // set url
    curl_setopt($curl, CURLOPT_URL, $uri);
    // send the request and save response to $response
    $response = curl_exec($curl);

    // stop if fails
    if(!$response) {
      die(\'Error: \"\' . curl_error($curl) . \'\" - Code: \' . curl_errno($curl));
    }
    var_dump($response);
  }

  // close curl resource to free up system resources
  curl_close($curl);

什么不起作用?有效负载/数据未提交。如果我在没有加密的情况下 tcpdump 命令行和 php 版本,我可以看到,命令行在期望:100-继续请求和HTTP/1.1 100 继续来自服务器的响应。 php 版本之后不做任何事情HTTP/1.1 100 继续响应并在达到超时后退出。

    标签: php curl


    【解决方案1】:

    来自documentation

    CURLOPT_PUT- true 用于 HTTP PUT 文件。要 PUT 的文件必须设置为 CURLOPT_INFILECURLOPT_INFILESIZE

    并且您没有使用任何文件来提供内容。

    你应该使用CURLOPT_CUSTOMREQUEST =&gt; 'PUT'


    这是从 Postman 导出的相同 cUrl 请求:

    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://blabla/blablabla',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'PUT',
      CURLOPT_POSTFIELDS =>'<valid json data>',
      CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='
      ],
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);
    echo $response;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多