首页 > PHP > PHP带Header的POST请求

PHP带Header的POST请求

时间:2023-02-14浏览次数:230
//调用
$data = array(
		"name"=>'123123',
		"password"=>'123123',
	);
$url = 'http://pjax.vip';
$header[] = 'content-type: application/json';
$a = $this->post($url,$header,$data);



/**
 * POST发送数据
 * @param String $url     请求的地址
 * @param Array  $header  自定义的header数据
 * @param Array  $data POST的数据
 * @return String
 */
function post($url,$data=[],$header=[]){
    $ch = curl_init();
    if(substr($url,0,5)=='https'){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, true);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    $response = curl_exec($ch);
    if($error=curl_error($ch)){
        die($error);
    }
    curl_close($ch);
  //var_dump($response);
    return $response;
}