php - 使用 php cURL 发送图像

标签 php curl

您好,我需要使用 PHP cURL 发送图像,尝试这样做:

$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_URL, $URL);
$postValues = array(
            'utf8' => $utf8,
            'authenticity_token' => $auth_token,
            'media_object[title]' => 'something',
            'media_object[source]' => '',
            'media_object[object_type]' => 0,
            'media_object[image]'=>'@/home/me/images/something.jpg',
            'captcha' => $captcha,
        );

$n = 0;
        $postStr = '';
        foreach ($postValues as $name => $value) {
            if ($n == 0)
                $postStr .= $name . '=' . $value;
            else
                $postStr .= '&' . $name . '=' . $value;
            $n++;
        }
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $postStr);
        curl_setopt($this->ch, CURLOPT_POST,1);
curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1");
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($this->ch, CURLOPT_COOKIEFILE, TMP.'cookies.txt');
        curl_setopt($this->ch, CURLOPT_COOKIEJAR, TMP.'cookies.txt');
curl_exec($this->ch);

但它不起作用。当然,我尝试使用此代码执行普通的 POST 请求并且它工作正常,只是当我尝试发布图像时它不起作用。

我已经通过 LIVE HTTP HEADERS 捕获了 header ,它看起来像这样: 这些是我使用带插件的 mozilla 捕获的正确 header ,因此 cURL 应该做同样的事情:

Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 218115
-----------------------------41184676334
Content-Disposition: form-data; name="utf8"

â
-----------------------------41184676334
Content-Disposition: form-data; name="authenticity_token"

0Je50mUpOMdghYgHPH5Xjd8UnbuvzzQLyyACfvGmVgY=
-----------------------------41184676334
Content-Disposition: form-data; name="media_object[title]"

Something
-----------------------------41184676334
Content-Disposition: form-data; name="media_object[source]"


-----------------------------41184676334
Content-Disposition: form-data; name="media_object[object_type]"

0
-----------------------------41184676334
Content-Disposition: form-data; name="media_object[image]"; filename="something.jpg"
Content-Type: image/jpeg

ÿØÿà

有什么问题吗?我尝试发送图像的网页返回消息“文件名不能为空!” 还尝试在 '@/home/me/images/something.jpg' 之后添加 ;filename="something.jpg"和 ;type="image/jpeg"

最佳答案

几周前我遇到了类似的问题,尝试更改文件的位置或权限。要找出哪些 header curl 发送试试这个:

curl_setopt(CURLINFO_HEADER_OUT, true);

请求后检索有关 header 的信息:

curl_getinfo($this->ch, CURLINFO_HEADER_OUT)

关于php - 使用 php cURL 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12305662/

相关文章:

php - AJAX 响应大小限制

excel - 在 VBA 中使用 curl 上传图像

Magento Paypal 错误 - payment_paypal_direct.log 中的持久沙箱 URL

c++ - 在 64 位 OSX 上构建 32 位 libcurl

php - 如何使用 ajax 在 Laravel 中删除单个记录

PHP 时区数据库损坏错误

php - WordPress SSL 通过 Cloudflare 重定向

php - 存储与 mysql 表的列相关的值的最佳方法?

php - 使用 http 客户端将文件发送到 API

php - 将curl与Google计算器一起使用总是返回0