PHP卷曲在标头中发送内容长度不起作用

时间:2014-09-16 10:59:33

标签: php curl content-length

我使用Curl将照片上传到实际网站。我可以从Fiddler看到标题看起来像这样:

Host: test.example.com
Proxy-Connection: keep-alive
Data-Type: json
Accept-Encoding: gzip, deflate
Content-Length: 62601
Content-Type: application/json
Accept-Language: en-us
Accept: application/json
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36

我使用上面的确切标题。我使用content-length

获取filesize的值
   $file = 'test.jpg';
   $file_size = filesize($file);

    $headers = array(
                "Host: test.example.com",
                "Proxy-Connection: keep-alive",
                "Data-Type: json",
                "Accept-Encoding: gzip, deflate",
                "Content-length: $file_size",
                "Content-Type: application/json",       
                "Accept-Language: en-us",
                "Connection: keep-alive",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36",
            );

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
$result = curl_exec($ch);

我实际上并不需要标题,脚本通常可以在没有标题的情况下运行,但是它太频繁地失败并且为了排除故障而将标题放入。

除了content-length之外,所有标题都可以正常工作。当我把它放入我得到服务器的响应,表明命令没有很好地形成(我不能在这里显示实际的响应)。我对content-length了解不多,但我相信这会告诉服务器文件的大小,这有助于确定上传完成。我想如果我有这个正常工作,它会增加我的脚本的稳定性。

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

如果您正在寻找使用curl发送文件,请将完整的filePath放在@之后,curl将处理其余文件。

$headers = array(
        "Proxy-Connection: keep-alive",
        "Data-Type: json",
        "Accept-Encoding: gzip, deflate",
        "Content-Type: application/json",       
        "Accept-Language: en-us",
        "Connection: keep-alive",
    );
$data = array(
    'fieldForFile' => '@'.  $filePath //Don't forget @ and the complete file path to the file
    'anyOtherFields' => $value,


);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
// Use CURLOPT_USERAGENT for setting the user agent
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST_DATA);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
$response = curl_exec($ch);

// Error handling
if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
} else {
    echo "Success";
}

curl_close ($ch);