lylovefl Back-End Dev Engineer

php处理发送post或者get请求

2016-11-23
php
 

php处理发送post或者get请求,写api接口时候用到。

代码

    public function get_url_contents($apiId, $data, $method="post", $data_type='json',     $timeout=60)
    {
        //获取apiId对应的url
        $url = Yii::$app->params['local_url'].Yii::$app->params['api_list']
        $ch = curl_init();
        if('get' == strtolower($method)){
            $url = is_array($data) ? $url.'?'.http_build_query($data) : $url . '?' .$data ;
            curl_setopt($ch, CURLOPT_URL, $url);
        }else {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json","charset=UTF-8"));
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the transfer as a string

        $output = curl_exec($ch);

        if($data_type == 'var_export') {
            $result = '' ;
            @eval("\$result=$output;");
            return $result ;
        }
        else
        {
            return $output ;
        }
    }

12月7日添加

因为项目很多需要用到https,上面代码访问https的时候每次都只会访问false,原因事当请求https的数据时,会要求证书,这时候,需要加上下面两个参数,从而规避ssl的证书检查。


curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);


上一篇 php导出txt文件

下一篇 beego-路由设置

Comments