在PHP中,Curl无法上传文件

3

我正在使用Brightcove API,将视频文件从我的服务器上传到我的Brightcove账户。以下是我使用的代码:

$fields = array(
    'json' => json_encode( array(
        'method' => "create_video",
        'params' => array(
            'video' => array(
                'name' => $video->submission_by_name.' '.time(),
                'shortDescription' => $video->submission_question_1
            ),
            "token" => $this->config->item('brightcove_write_token'),
            "encode_to" => "MP4",
            "create_multiple_renditions" => "True"
        ))
    ),
    'file' => new CURLFile(FCPATH.'assets/uploads/submitted/'.$video->filename)
);

//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $this->config->item('brightcove_write_endpoint'));
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute post
$result = json_decode(curl_exec($ch));

这在本地可以正常工作,但是live服务器正在运行PHP 5.3,所以我不能使用new CURLFile()

我该如何以适用于PHP 5.3.3的方式发送文件? 我尝试使用@语法来更改文件字段,就像这样:

'file' => '@' . FCPATH.'assets/uploads/submitted/'.$video->filename

但是似乎不起作用,API返回错误信息:

FilestreamRequiredError: upload requires a multipart/form-data POST with a valid filestream

看起来文件没有被发布。

我也尝试像这样复制curl_file_create函数:

private function custom_curl_file_create($filename, $mimetype = '', $postname = '')
{
    if($mimetype=='') {
        $mimetype = mime_content_type($filename);
    }
    return "@$filename;filename="
        . ($postname ?: basename($filename))
        . ($mimetype ? ";type=$mimetype" : '');
}

然后执行:

'file' => $this->custom_curl_file_create(FCPATH.'assets/uploads/submitted/'.$video->filename)

然而这也不起作用,API 返回之前相同的错误

1个回答

0

显然,在多部分POST请求中存在“@”问题。我找到了以下信息,解决了这个问题:

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
* For safe multipart POST request for PHP5.3 ~ PHP 5.4.
* 
* @param resource $ch cURL resource
* @param array $assoc "name => value"
* @param array $files "name => path"
* @return bool
*/
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v), 
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data, 
        ));
    }

    // generate safe boundary 
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

这是从PHP CURLFile::__construct文档的用户贡献笔记部分检索到的。

我像这样使用它,它有效:

$fields = array(
    'json' => json_encode( array(
        'method' => "create_video",
        'params' => array(
            'video' => array(
                'name' => $video->submission_by_name.' '.time(),
                'shortDescription' => $video->submission_question_1
            ),
            "token" => $this->config->item('brightcove_write_token'),
            "encode_to" => "MP4",
            "create_multiple_renditions" => "True"
        ))
    )
);

$files = array(
    'file' => FCPATH.'assets/uploads/submitted/'.$video->filename
);

//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $this->config->item('brightcove_write_endpoint'));
$this->curl_custom_postfields($ch, $fields, $files);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute post
$result = json_decode(curl_exec($ch));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接