学习笔记

  > CURL post data 通用方法

CURL post data 通用方法

private function http_request($url,$method="GET", $data = null, $header = null)
	{
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    if(!empty($header)){
	        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	        curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
	    }
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    if (!empty($data)) {
	        curl_setopt($curl, CURLOPT_HTTPGET, 1);
	        curl_setopt($curl, CURLOPT_POSTFIELDS,http_build_query($data));
	    }
	 
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	    $output = curl_exec($curl);
	    if (curl_errno($curl)) {
			return curl_error($curl);
		}

	    curl_close($curl);
	    return $output;
	}

这是带header的

function login()
	{
		$mobile = $this->input->get('mobile',TRUE);
		$mobilecode = $this->input->get('mobilecode',TRUE);
		$uniqueId = $this->input->get('uid',TRUE);
	    $headersLogin = array(
	        "X-Ca-Stage:TEST",  
	        "Authorization:APPCODE 398e4de4d3694c9d93e9b6394b8fad2e",
	        "Content-Type:application/x-www-form-urlencoded; charset=utf-8",
	        "channelId:1",
	        "empid:H5LINE",
	    );  
	    $urlLogin = "https://api.xxx.com/v1/auth/nuskin/user/b2cmember/auth";
	    $dataLogin = array(
	        "userCode"          => $mobile,
	        "verifyCode"        => $mobilecode,
	        "trench"            => "wx",
	        "loginType"         => "mobile",
	        "uniqueId"          => $uniqueId,
	        "loginFlag"         => 2,
	        "loginSource"       => 2,
	    );

	    $resDataLogin = $this->http_request($urlLogin,"POST",$dataLogin,$headersLogin);


	    $notice = array('status'=>200,'msg'=>'操作成功','res'=>json_decode($resDataLogin,TRUE));
	    echo json_encode($notice,JSON_UNESCAPED_UNICODE);
	    exit;
	}

就这么多了,反正是一个值得记录的传header和body以及get,post共同的方法

发布时间:2023-03-15,18:41:29

curl经典php例子。参考aligate网关相关。

作者:澎蠡

让学习成为一种习惯,让知识交流变成一种生活方式。