php curl 请求封装

/**
 * curl 封装函数
 * @param  string $url   请求地址
 * @param  string $data   请求数据
 * @param  string $type  请求方式  默认为GET
 * @return string
 */
function jbtm_curl($url, $data = '', $type = 'GET', $headers=[],  $timeout=10)
{
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    if($headers){
        $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    }

    //POST 方式
    if("POST" == strtoupper($type)){
        curl_setopt ( $ch, CURLOPT_POST, true );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    }
    $result = curl_exec ( $ch );
    curl_close ( $ch );
    return $result;
}

 

posted @ 2020-05-25 12:03  phpwyl  阅读(423)  评论(0编辑  收藏  举报