【问题标题】:How to send form fields and a file using PHP Curl?如何使用 PHP Curl 发送表单字段和文件?
【发布时间】:2010-04-15 10:57:44
【问题描述】:

我正在尝试使用 php curl 将表单字段和文件发送到 Web 服务。该表单已从浏览器传递到代理 php 客户端 Web 应用程序,我正在尝试将其转发到 Web 服务。

当我像这样将数组传递给 curl_setopt 时:

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

我收到了一个 Array to String 的通知,尽管它是用来接收一个数组的。这是我在构造函数中传递给 $this->fields 的数组。

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

如果我使用http_build_query 传递一个字符串,我的网络服务会抱怨没有多部分/表单数据。

如果我随后使用 curl_setopt 强制使用 multipart/form enctype,我会收到一条错误消息,指出没有边界:

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

有什么想法吗?

【问题讨论】:

    标签: php curl


    【解决方案1】:

    数组到字符串通知你有以下代码:

    $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”操作中发布的完整数据。
    要发布文件,请在文件名前添加 @ 并使用完整路径。
    这既可以作为像'para1=val1&para2=val2&...' 这样的urlencoded 字符串传递,也可以作为以字段名称作为键、字段数据作为值的数组传递。
    如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data

    【讨论】:

    • 谢谢,我现在用 @ 传递文件名,但我仍然收到多部分边界错误。
    【解决方案2】:

    试试这个,

    $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 2012-05-29
      • 2011-09-03
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多