将图像添加到数组并通过curl提交


adding image to an array and submit it via curl

我有麻烦从url发送图像到远程主机使用curl。

// assemble full image path
foreach ( $respArr[ 'imgs' ] as $k => $v) {
    $car[ 'photos' ][ $k ] = file_get_contents( 'http://' . $v[ 'ipt' ] . '/im/im-' . $v[ 'ikey' ] ); // full url?
}

问题是,我不明白浏览器如何发送图像,它创建数组,比这个数组的内容是不可见的,当我试图转储$_POST。

我认为你可以这样做:

$image       = file_get_contents(PATH_TO_IMAGE);
$imageBase64 = base64_encode($image);

现在你可以像普通数据一样通过curl传输图像
传输完成后,您应该在浏览器中按如下方式使用

print '<img src="data:image/png;base64' . $imageBase64 .'">';

image/TYPE:您还应该传输正确的图像类型:gif, jpg…

希望有帮助

使用curl模拟POST-submit的一种粗糙但足够9/10倍的方法如下:

$ch = curl_init();
$opts = [
    'CURLOPT_HEADER         => true,
    'CURLOPT_RETURNTRANSFER => true,
    'CURLOPT_URL            => 'http://your.dom/submit/route',
    'CURLOPT_POST           => true,
    'CURLOPT_POSTFIELDS     => [
        'image'  => new 'CURLFile('/path/to/img.png'),
        //pre 5.5
        'image2' => "@/path/to/img.png",
        //fields like foo[]
        'foo'    => [
            'val1',
            'val2',
            '',//empty
        ],
        'otherField' => '123',
        //fields like user[name] and user[lastName]
        'user'       => [
            'name'     => 'John',
            'lastName' => 'Doe',
        ],
    ]
];
curl_setopt_array($opts);
$response = curl_exec($ch);
$debugInfo = curl_getinfo($ch);
//error:
$message = curl_error($ch);
$errNr = curl_errno($ch);
curl_close($ch);
对于使用远程图像(URL),您可能需要考虑构造tempnam函数:
//construct file array:
$photos = [];//files you'll add to your curl request
foreach ($files as $v) {
    $tmpFile = tempnam('/tmp/curlfiles');
    //write image to tmp file
    file_put_contents(
        $tmpFile,
        //contents == get the image
        file_get_contents(
            'http://' . $v['ipt'] . '/im/im-' . $v['ikey']
        )
    );
    //add CURLFile resource
    $photos[] = new CURLFile($tmpFile);
    //or $photos[] = "@$tmpFile";...
}
//then, in $opts:
$opts['CURLOPT_POSTFIELDS]['photos'] = $photos;
//curl_setopt_array && curl_exec etc...

CURLFile::__construct的手册页上,有一些片段你可能能够使用,如果你没有CURLFile在你的处置,但看到你已经运行5.5,这不应该是一个问题