【问题标题】:adding image to an array and submit it via curl将图像添加到数组并通过 curl 提交
【发布时间】:2015-08-04 09:17:33
【问题描述】:

我无法使用 curl 将图像从 url 发送到远程主机。其他一切正常。

// 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 时,这个数组内容对我是不可见的。

欢迎对此领域的任何澄清:)

【问题讨论】:

  • 你试过using the CURLFile class吗?或者,如果您使用的是 EOL 的 PHP 版本,请使用 @'/path/to/file'?
  • @EliasVanOotegem 我正在模仿表单中的普通用户帖子。我需要像浏览器一样构建php数组并将其提交到我的api。
  • @EliasVanOotegem 这似乎是正确的方向。虽然信息很少,但似乎 php 5.5 的情况发生了变化
  • 发布了一个答案,展示了如何使用 curl 模拟 POST 请求,提交表单

标签: php post curl


【解决方案1】:

我认为你可以这样做:

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

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

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

图像/类型:您还应该传输正确的图像类型:gif、jpg...

希望有帮助:)

【讨论】:

  • 嗨,我认为这还不够。我正在模仿普通用户使用 curl 将浏览器发布到页面。
【解决方案2】:

使用 curl 模拟 POST 提交的粗略但足够 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),您可能需要考虑构建the tempnam function

//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 可供您使用,您可能可以使用一些 sn-ps,但鉴于您已经在运行 5.5,那应该不是问题

【讨论】:

  • 谢谢!但这行不通。由于我正在使用远程 API,远程服务器只接收发送服务器的临时文件路径...
猜你喜欢
  • 2020-04-23
  • 2011-12-28
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
相关资源
最近更新 更多