将CURL命令转换为PHP Curl

时间:2018-07-09 20:54:11

标签: php curl

我有以下命令可以在PHP中运行,并且可以按预期工作:

$params = [
        'file' => $xmlLocalPath,
        'type' => 'mismo',
        'file_type' => $xmlFile['file_type'],
        'filename' => $xmlFile['file_name']
    ];

$cmd =
        'curl -X POST ' . $this->outboundBaseURL . 'document \
        -H "Accept: application/json" \
        -H "Authorization: Bearer ' . $this->token . '" \
        -H "Cache-Control: no-cache" \
        -H "Content-Type: multipart/form-data" \
        -F "file=@' . $params['file'] . ';type=' . $params['file_type'] . '" \
        -F "type=' . $params['type'] . '" \
        -F "filename=' . $params['filename'] . '"';
    exec($cmd, $result);

我需要使用PHP的curl库才能使其正常工作,但我无法使其正常运行。我使用的是PHP 5.6,这是我现在拥有的:

$params = [
        'file' => $xmlLocalPath,
        'type' => 'mismo',
        'file_type' => $xmlFile['file_type'],
        'filename' => $xmlFile['file_name']
    ];

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $this->outboundBaseURL . 'document',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_HTTPHEADER => [
            'Accept: application/json',
            'Authorization: Bearer ' . $this->token,
            'Cache-Control: no-cache',
            'Content-Type: multipart/form-data'
        ]
    ]);

    curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking

    $response = curl_exec($ch);
    $err = curl_error($ch);

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

我知道问题一定与POSTFIELDS有关,尤其是文件,但是我没有展示如何以适当的方式为PHP CURL提供参数,以便文件和其他参数的发送与原始的curl调用。我知道PHP Curl中不推荐使用“ @”方法,而且我也尝试过将curl_file_create与本地文件一起使用

1 个答案:

答案 0 :(得分:1)

尝试再添加一个参数:

CURLOPT_POST => 1