如何使用PHP Curl发送表单域和文件?

问题描述:

我试图发送表单域和文件到使用PHP卷曲的Web服务。该表单已经从浏览器传递到代理PHP客户端Web应用程序,我试图将其转发到Web服务。如何使用PHP Curl发送表单域和文件?

当我传递一个数组curl_setopt这样的:

curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->fields);

我得到一个数组为String通知虽然是指把一个数组。这是我的数组传递给构造函数中的$ this->字段。

$fields = array('title'=>$title, 
'content'=>$content, 
'category'=>$category, 
'attachment'=>$_FILES['attachment']); 

如果我通过使用http_build_query我的web serivce抱怨没有多/表单数据的字符串。

如果我再用力使用curl_setopt多部分/表单的enctype我得到一个错误说没有边界:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

任何想法?

数组串注意到你有下面的代码:

$fields = array(
    'title'=>$title, 
    'content'=>$content, 
    'category'=>$category, 
    'attachment'=>$_FILES['attachment'] 
); 
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields); 

是不是因为你传递一个数组作为第三个参数curl_setopt:那是因为你传递一个数组attachment


如果你想传递一个文件这种方式,你应该通过它的绝对路径,之前预先以待@它:

$fields = array(
    'title'=>$title, 
    'content'=>$content, 
    'category'=>$category, 
    'attachment'=> '@' . $_FILES['attachment'] 
); 
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields); 

(这是假设$_FILES['attachment']包含的完整路径你的文件 - 由你来改变这种代码,以便它使用正确的数据,如果需要的话)


作为参考,引用的curl_setopt手册页,为CURLOPT_POSTFIELDS选项:

要在HTTP“POST”操作中发布的完整数据。
要发布文件,请在文件前加上@并使用完整路径。
这可以作为urlencoded字符串(如'para1=val1&para2=val2&...')传递,也可以作为字段名称作为键和字段数据作为值的数组传递。
如果value是一个数组,Content-Type标题将被设置为multipart/form-data

+0

谢谢,我现在正在与@文件名,但我仍然得到多边界错误。 – blank 2010-04-15 11:32:50

试试这个,

$filePath = "abc\\xyz.txt";   

$postParams["uploadfile"] = "@" . $filePath; 


     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
     curl_setopt($ch, CURLOPT_URL, 'https://website_address'); 
     curl_setopt($ch, CURLOPT_POST, 1); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $response = curl_exec($ch); 

     if (curl_errno($ch)) 
      { 
       echo curl_error($ch);    
       exit();       
      } 
     curl_close($ch);