您现在的位置是:PHP发送POST请求

PHP发送POST请求

PHP 日期:2016-11-29点击:3107
//请求并返回内容
public static function curlPostData($url, $data = array(), $timeout = 5) {
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'MZAdmin');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8')); //构造IP 
    //curl_setopt($ch, CURLOPT_REFERER, "https://jishu8.net"); //构造来路 
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    //POST数据
    if( $data ) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //判断是否为json
    if( is_string($data) && is_array(json_decode($data, true)) ) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: '.strlen($data)
                )
       );
    }
    $response = curl_exec($ch);
    if( $response === FALSE ) {
        echo "cURL Error: ".curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    if( $httpCode == 200 ) {
        return $response;
    } else {
        $err = array('errcode' => $httpCode, 'errmsg' => 'cURL Error', 'errdesc' => $httpInfo);
        return json_encode($err, JSON_UNESCAPED_UNICODE);
    }
}
标签: PHP

站长简介

姓名:喻理
微信:yuli0927
邮箱:yuli0927@126.com
不懂业务的运维工程师不是一个好程序员。

分类

最新文章

热门文章