PHP POST CURL上传图片

来源:互联网 发布:怎么获取数据库的值 编辑:程序博客网 时间:2024/04/30 10:04
<pre name="code" class="php">function _curl_multipart_post($url, $post_data, $file_fields = array(), $timeout=30)    {        $result = array('errno' => 0, 'errmsg' => '', 'result' => '');        $ch = curl_init();//set various curl options first// set url to post tocurl_setopt($ch, CURLOPT_URL, $url);// return into a variable rather than displaying itcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//set curl function timeout to $timeoutcurl_setopt($ch, CURLOPT_TIMEOUT, $timeout);        curl_setopt($ch, CURLOPT_VERBOSE, false);//set method to postcurl_setopt($ch, CURLOPT_POST, true);// disable Expect header// hack to make it working$headers = array("Expect: ");curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);// initialize result post array$result_post = array();//generate post string$post_array = array();$post_strings = array();if (!is_array($post_data)) {            $result['errno'] = 5;            $result['errmsg'] = 'Params error.';            return json_encode($result);// return false;}foreach($post_data as $key=>$value) {$post_array[$key] = $value;$post_strings[] = urlencode($key)."=".urlencode($value);}$post_string = implode("&", $post_strings);// set post string        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);// set multipart form data - file array field-value pairsif (!empty($file_fields)) {foreach($file_fields as $key => $value) {if (strpos(PHP_OS, "WIN") !== false) {                    $value = str_replace("/", "\\", $value); // win hack                }$file_fields[$key] = "@".$value;}}// set post data$result_post = array_merge($post_array, $file_fields);if(class_exists("CURLFile")){//zjb 修复新版本PHP引来的Bug$result_post['Filedata'] = new CURLFile($result_post['filepath']);}curl_setopt($ch, CURLOPT_POSTFIELDS, $result_post);        // print_r($result_post);//and finally send curl request$output = curl_exec($ch);        $result['result'] = $output;        // print_r($result);if (curl_errno($ch)) {            if (0) {echo "Error Occured in Curl\n";echo "Error number: " .curl_errno($ch) ."\n";echo "Error message: " .curl_error($ch)."\n";}            $result['errno'] = curl_errno($ch);            $result['errmsg'] = curl_error($ch);// return false;} else {// return $result;}        curl_close($ch);                return $result;}


                                             
0 0