PHP通过curl模拟POST上传文件,5.5之前和之后的区别

首先先要着重提一下,只要是做和项目有关的开发,首先按把环境中各个服务的版本保持一致,否则出些莫名其妙的错我,让你百爪挠心却不知哪里的问题。这里就要说下curl_setopt($ch, CURLOPT_POSTFIELDS, $array) 这个方法上传,在5.5之前是可以用的,5.5的时候已经设置为deprecated,会有下面的提示,5.6的时候已经被删除。所以5.6版本的可能不能直接使用网上的一些代码。

curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead

因此这部分要根据版本判断下,修改为下面

/**
 * CURL 上传文件
 * @param $url 处理上传文件的url
 * @param array $post_data post 传递的参数
 * @param array $file_fields 上传文件的参数,支持多个文件上传
 * @param int $timeout 请求超时时间
 * @return array|bool
 */
function curl_upload($url, $post_data=array(), $file_fields=array(), $timeout=600) {
    $result = array('errno' => 0, 'errmsg' => '', 'result' => '');
    
    $ch = curl_init();
    //set various curl options first

    // set url to post to
    curl_setopt($ch, CURLOPT_URL, $url);

    // return into a variable rather than displaying it
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //set curl function timeout to $timeout
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    //curl_setopt($ch, CURLOPT_VERBOSE, true);

    //set method to post
    curl_setopt($ch, CURLOPT_POST, true);

    // disable Expect header
    // hack to make it working
    $headers = array("Expect: ");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    //generate post data
    $post_array = array();
    if (!is_array($post_data)) {
        $result['errno'] = 5;
        $result['errmsg'] = 'Params error.';
        return $result;
    }
    
    foreach ($post_data as $key => $value) {
        $post_array[$key] = $value;
    }

    // set multipart form data - file array field-value pairs
    if(version_compare(PHP_VERSION, '5.5.0') >= 0) {
        if (!empty($file_fields)) {
            foreach ($file_fields as $key => $value) {
                if (strpos(PHP_OS, "WIN") !== false) {
                    $value = str_replace("/", "\\", $value); // win hack
                }
                $file_fields[$key] = new CURLFile($value);
            }
        }
    } else {
        if (!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);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $result_post);
    // print_r($result_post);

    //and finally send curl request
    $output = curl_exec($ch);
    $result['result'] = $output;
    
    if (curl_errno($ch)) {
        echo "Error Occured in Curl\n";
        echo "Error number: " . curl_errno($ch) . "\n";
        echo "Error message: " . curl_error($ch) . "\n";
        return false;
    } else {
        return $result;
    }
    curl_close($ch);
}

 

posted @ 2016-11-18 16:31  達達尼亞  阅读(4435)  评论(0编辑  收藏  举报