php - Curl 不在 PHP 中发布文件

标签 php codeigniter curl codeigniter-3 brightcove

我正在使用 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));

这是在本地工作,但是实时服务器运行的是 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 返回与之前相同的错误

最佳答案

显然,多部分 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 documentation 的用户贡献的注释部分检索到的

我是这样用的,效果很好:

$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));

关于php - Curl 不在 PHP 中发布文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266329/

相关文章:

php - 手动设置谷歌的 pubsubhubbub - 没有验证/提要结果失败

php - 单独的 Angular 2 客户端和 Laravel PHP 后端的推送通知

php - 使 cURL 在收到数据时写入数据

php - 相当于 PHP preg_split() 的 JavaScript

php - 在关系型 mysql 数据库中的多个表中执行多个插入查询的正确方法是什么?

php - Paypal 沙盒 IPN "Email does not match seller"

php - Codeigniter 从数据库获取结果

php - 在循环内将数组添加到多维数组

使用 Curl 下载文件的 Bash 脚本

c++ - Mac OS X 上的 darwinssl 库位置是什么?