通过CURL将图像发布到表单

时间:2011-09-22 01:15:20

标签: php curl

我在寻找以下问题的解决方案时遇到了困难,我需要使用curl在网站上提交表单,但是还需要将图片上传到正常的输入文件字段

<input type="file" name="image"/>

我有一个类,curl函数定义如下

function fetch($url, $username='',  $data='', $proxy=''){


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, true);


    if(isset($proxy)) {     
    curl_setopt($ch,CURLOPT_TIMEOUT,30); 
    curl_setopt($ch, CURLOPT_PROXY, $proxy); 
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, $proxy);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'proxyadmin:parola');

    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_FRESH_CONNECT,true);

    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/3.0 (compatible; MSIE 6.0; Windows NT 5.0)"); 

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    if($username) {
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie/{$username}.txt");

    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie/{$username}.txt");
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 


    if (is_array($data) && count($data)>0){

        curl_setopt($ch, CURLOPT_POST, true);

        $params = http_build_query($data);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

    }


    if (is_array($this->headers) && count($this->headers)>0){

        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

    }



    $this->result = curl_exec($ch);
    $curl_info = curl_getinfo($ch);
    $header_size = $curl_info["header_size"];
    $this->headers = substr($this->result, 0, $header_size);
    $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $this->error = curl_error($ch);

    curl_close($ch);    

}

有人可以帮助我吗?非常失落

1 个答案:

答案 0 :(得分:1)

如果您更改以下代码块:

// from
if (is_array($data) && count($data)>0){
    curl_setopt($ch, CURLOPT_POST, true);
    $params = http_build_query($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}

// to
if (is_array($data) && count($data)>0) {
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}

要让它发布用户上传的文件,请按以下方式设置数据:

// make sure $_FILES['file'] has been uploaded and is valid
$data = array('field' => 'value',
              'name' => 'test',
              'email' => 'something',
              'file' => '@' . $_FILES['file']['tmp_name']
             );

fetch($url, $username, $data);

这将告诉curl发送带有文件上传的表单帖子。通过将post字段设置为数组并将&amp; 添加到作为数组值的文件的完整路径,curl将发送带有文件上载的multipart / form-data post请求

请参阅curl file upload example