php cURL POST内容长度始终显示为-1

时间:2019-01-18 06:35:25

标签: php curl post http-content-length

我不熟悉使用cURL向服务器发送POST请求,但是服务器始终显示content-length为-1,我的代码如下:

$data = array(
    'data'  =>  'Testing data',
    'name'  =>  'Testing',
    'no'    =>  '1234'
);
foreach($data as $key=>$value) { $data_string .= $key.'='.$value.'&'; }
$data_string = trim($data_string, '&'); 
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, Yii::$app->request->post('url'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_SSLVERSION, 6); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Length: ' . strlen($data_string)]); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close($ch);
return $result;

为什么内容长度总是显示-1,谢谢〜

2 个答案:

答案 0 :(得分:0)

已更新

请运行以下更新的代码并发布结果:

$postData = array(
'data' => Yii::$app->request->post('data'),
'mac' => Yii::$app->request->post('mac'),
'ksn' => '1'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
curl_setopt($ch,CURLOPT_URL, Yii::$app->request->post('url'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1); //Add this line so we can grab the headers that were sent with your request.
curl_setopt($ch, CURLOPT_FAILONERROR, 1); //Helps with http errors.
curl_setopt($ch, CURLOPT_VERBOSE, 1); //This shows the response headers in the response.
curl_setopt($ch, CURLOPT_HEADER, 1); //Oppps
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

if(curl_exec($ch) === false){

echo 'There was an error with your request.<br>';
echo 'Here are the curl errors:<br>';
echo curl_error($ch) . '<br><br>';

}else{

  echo 'There were no errors with the request.<br>';
  $result = curl_exec($ch);
  echo $result;

}

//Get your sent headers:
$info = curl_getinfo($ch);
echo '<pre>';
echo 'Here are the headers that you sent:<br>';
print_r($info);
echo '</pre>';

curl_close($ch);

return $result;

答案 1 :(得分:0)

这已在注释中建议。我添加了一个内容类型(如果您的内容类型不同,请根据需要进行更改)。

   $data = array(
        'data'  =>  'Testing data',
        'name'  =>  'Testing',
        'no'    =>  '1234');
    $data_string = json_encode($data); 
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, Yii::$app->request->post('url'));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_SSLVERSION, 6); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . mb_strlen($data_string) )
            ); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;