Reg:如何使用php在CURL中发送多个文件和其他post params

时间:2014-01-22 12:34:54

标签: php curl

我正在尝试使用PHP中的curl向REST服务发布请求,但它无效。下面列出的是我尝试过的一段代码。

function curl_post_data($log,$url){
    $clientid= 18;
    $userid = 1614;

    $voicesample1filename = realpath("RecordFiles/utterance1.wav");
    $voicesample2filename = realpath("RecordFiles/utterance2.wav");
    $voicesample3filename = realpath("RecordFiles/utterance3.wav");

    $payload['sessionid'] = '13738B27-C664-57B0-2ABF-8873914E971A';
    $payload['clienid'] = $clientid;
    $payload['userid'] = $userid;
    $payload['type'] = 8;
    $payload['action'] = 'registration';

    // build multipart
    $payload = http_build_query($payload);

    if ( is_file($voicesample1filename) ) {
        $log->LogInfo("File '" . $voicesample1filename . "' exists");
    } else {
        $log->LogInfo("File '" . $voicesample1filename . "' does not exists");
    }

    $params  = "--ABC1234\r\n"
    . "Content-Type: application/x-www-form-urlencoded\r\n"
    . "\r\n"
    . $payload . "\r\n"
    . "--ABC1234\r\n"
    . "Content-Type: audio/wav\r\n"
    . "Content-Disposition: attachment; utterance1=\"attachment1.wav\"\r\n"
    . "\r\n"
    . file_get_contents($voicesample1filename) . "\r\n"
    . "--ABC1234\r\n"
    . "Content-Type: audio/wav\r\n"
    . "Content-Disposition: attachment; utterance2=\"attachment2.wav\"\r\n"
    . "\r\n"
    . file_get_contents($voicesample2filename) . "\r\n"
    . "--ABC1234\r\n"
    . "Content-Type: audio/wav\r\n"
    . "Content-Disposition: attachment; utterance3=\"attachment3.wav\"\r\n"
    . "\r\n"
    . file_get_contents($voicesample3filename) . "\r\n"
    . "--ABC1234--";

    $log->LogInfo("Request is :" .$params);

    $first_newline      = strpos($params, "\r\n");
    $multipart_boundary = substr($params, 2, $first_newline - 2);
    $request_headers    = array();
    $request_headers[]  = 'Content-Length: ' . strlen($params);
    $request_headers[]  = 'Content-Type: multipart/form-data; boundary='. $multipart_boundary;

    $log->LogInfo("PayLoad Array is :" .print_r($payload,true));

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    //curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $reply = curl_exec($ch);

    $arrayOfResult=json_decode($reply,true);
}

如果我执行代码,我收到多部分请求错误。

1 个答案:

答案 0 :(得分:0)

您无需手动使用“内容处理”功能。 Curl在找到要发送的文件时自动执行此操作。对于这种情况,您可以考虑以下示例。如果您使用与代码类似的东西,curl将调整所需的多部分标题。

$params = array("name" => "some-name",
            "id" => "1231",
            "file1" => "@c:/temp/file1.wav",
            "file2" => "@c:/temp/file2.wav"
            );