如何为curl_file_create函数使用文件内容而不是文件名?

时间:2019-06-19 09:28:43

标签: php file curl

curl_file_create函数的第一个参数是文件名。有没有办法直接使用文件的内容?
我不想在临时文件中写入内容,并在函数中使用该文件名。

更多展开:
我使用$image = file_get_contents('http://example.com/image.jpg');函数从URL获取图像,所以现在有一个$image变量,具有二进制图像内容,获取后,我需要将该图像作为表单的一部分立即发布到另一个URL,而无需使用磁盘上的临时文件。

1 个答案:

答案 0 :(得分:0)

任何想这样做的人:毫无疑问,这不值得麻烦。当然有可能,但是您几乎可以肯定要使用tmpfile()技巧,例如,如果您有一个名为$file_content的变量要上传为文件,但没有文件,做

<?php
$file_content = "the content of the *file* i want to upload, which does not exist on disk";
$file_name = "example.bin";
$tmph = tmpfile(); // will create a file in the appropriate temp folder when an unique filename
fwrite($tmph, $file_content);
$tmpf = stream_get_meta_data($tmph)['uri'];
$ch = curl_init('http://target_url/');
curl_setopt_array($ch, array(
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'file' => new CURLFile($tmpf, 'application/octet-stream', $file_name)
    )
));
curl_exec($ch);
fclose($tmph); // thanks to tmpfile() magic, the file is automatically deleted when fclosed()'d
unset($tmph, $tmpf); // unset() is not needed, but this is the end of the tmpfile()-trick.

..幸运的是,只要上传速度很快并且我们不调用fflush($ tmph);,文件可能永远也不会接触实际的磁盘,它只会在IO中创建缓存,计划稍后再写入磁盘,然后从io缓存中删除-此代码也受PHP的垃圾收集器保护,如果代码中有未捕获的异常/错误停止执行,PHP的垃圾收集器将删除该文件为了我们。

但是,以下是通过使用用户级PHP代码创建Multipart/form-data请求来实际上以Multipart/form-data格式上传文件而又不创建磁盘文件的方法:

用法示例:

<?php

// normal php-way: 
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL=>'https://example.com/',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'sample_variable' => 'anything',
        'file' => new CURLFile("path/to/file.txt")
    )
));
curl_exec($ch);
curl_close($ch);
// shitty_multipart-way: 
$post_data = array();
$tmp = new shitty_multipart_variable();
$tmp->post_name = 'sample_variable';
$tmp->content = 'anything';
$post_data[] = $tmp;
$tmp = new shitty_multipart_file();
$tmp->post_name = 'file';
$tmp->post_file_name = "file.ext";
$tmp->content = 'contents of file.ext';
$post_data[] = $tmp;
$content_type_header="";
$post_body=shitty_multipart_form_data_generator($post_data,$content_type_header);
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL=>'https://example.com/',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => $post_body,
    CURLOPT_HTTPHEADER=>array(
        $content_type_header
    )
));
curl_exec($ch);
curl_close($ch);

实现:

class shitty_multipart_file
{
    public $post_name = "";
    public $file_name = "";
    public $content_type = "application/octet-stream";
    public $content = "";
    public $additional_headers = [];
}
class shitty_multipart_variable
{
    public $post_name = "";
    public $content = "";
    public $additional_headers = [];
}
function shitty_multipart_form_data_generator(array $postfields, string &$out_content_type_header): string
{
    // Content-Type: multipart/form-data; boundary=------------------------7b5b9abe8c56fd67
    // same boundary format as used by curl
    $boundary = "------------------------" . strtolower(bin2hex(random_bytes(8)));
    $out_content_type_header = 'Content-Type: multipart/form-data; boundary=' . $boundary;
    $body = "";
    foreach ($postfields as $unused => $post) {
        $body .= $boundary . "\r\n";
        if (is_a($post, 'shitty_multipart_variable')) {
            $body .= "Content-Disposition: form-data; name=\"{$post->post_name}\"\r\n";
            foreach ($post->additional_headers as $header) {
                $body .= $header . "\r\n";
            }
            $body .= "\r\n";
            $body .= $post->content . "\r\n";
        } elseif (is_a($post, 'shitty_multipart_file')) {
            $body .= "Content-Disposition: form-data; name=\"{$post->post_name}\"; filename=\"{$post->file_name}\"\r\n";
            $body .= "Content-Type: " . $post->content_type . "\r\n";
            foreach ($post->additional_headers as $header) {
                $body .= $header . "\r\n";
            }
            $body .= "\r\n";
            $body .= $post->content . "\r\n";
        } else {
            throw new \InvalidArgumentException("postfields key {$unused} is not an instance of shitty_multipart_variable NOR an instance of shitty_multipart_file!");
        }
    }
    $body .= $boundary . "--\r\n";
    return $body;
}