使用CURL和Curlfile()获得POST多部分/表单数据的完整示例

时间:2015-07-10 04:51:41

标签: php post curl heroku multipartform-data

我现在已经挣扎了几天。 (顺便说一句,我是cURL的新手)

我的移动应用程序开发人员在Heroku上设置了API,我使用以下命令发布表单数据:

 public function do_add() {

                $Name           =   $this->input->post('Name');
                $Email          =   $this->input->post('Email');
                $Password       =   $this->input->post('Password');

                $txt             =  "Created";


                $url = 'https://myfullurl.com/api/users/';


                $fields = array(
                    'name'                      =>  $Name,
                    'email'                     =>  $Email,
                    'password'                  =>  $Password,
                    'role'                      =>  'driver'
                );

                $result = $this->scripts->api_add($url, $fields);

                        $this->session->set_userdata('Success',"Record Has Been Successfully ".$txt."...");
                        redirect(base_url().'mmsadmin/users/view_all'); 

  }

所以,当我发布数据时,Codeignitor的功能收到它并将其发布到我的模型函数下面:

 public function api_add($url, $fields){

$fields_string = "";
                //url-ify the data for the POST
                foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
                rtrim($fields_string, '&');

                //open connection
                $ch = curl_init();

                //set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);

                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, count($fields));
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $this->session->userdata('Token')));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                $result = json_decode($content = curl_exec($ch));
                curl_close($ch);

                return $result;

}

最重要的是工作正常。现在我需要能够用它发送文件。一直在谷歌搜索,发现一些-F命令,并使用'@'发送它,但当我尝试我的服务器它给我错误,这个方法折旧,我应该使用curlfile()

你们其中一个天才能改变我的功能,以准确地展示如何做到这一点。因为我笨手笨脚,像无头鸡一样四天跑来跑去:(

谢谢你们

1 个答案:

答案 0 :(得分:0)

您正在使用的curl文件发送方法是从php5折旧的,您应该使用curlfile类。

transform: matrix(0.21130913087034978,0.45315389351832497,-0.45315389351832497,0.21130913087034978,310.61081520146786,-40.000898954115684)

上面是面向对象的样式,另一个是过程样式,如下所述:

    // Create a cURL handle
    $ch = curl_init('http://example.com/upload.php');

    // Create a CURLFile object
    $cfile = new CURLFile('filename.fileTpye');

    // Assign POST data
    curl_file_create('filename.fileTpye');
   // Assign POST data 
    $data =     array('test_file' =>$cfile,'name'=>'test','anotherData'=>'abc');
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    // Execute the handle
    curl_exec($ch);

有关详细信息,请参阅php curlFile手册。