php curl header头

工作中第一次用到header做个记录

工作中需要在heaer里面加上

Authorization 用来验证身份
public function index()
    {
        $url = "http://te33333.com";
        $param['username'] = "uduje";
        $param['password'] = "123456";
        $header[] = "Authorization:Basic ZWNjbGllbnQ6ZWXQ=";//我已开始把authorization写到了key里面就出错了
        $result = $this->request_post($url,$param,$header);
        dump($result);
        //$this->display();
    }
public function request_post($url = '', $param = '',$header=0) {
        if (empty($url) || empty($param) || empty($header)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//指定地址
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header输出,0不输出1输出
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header输入
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);//要求结果为字符串且输出到屏幕上,0输出1不输出
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
        
    }

post如果要提交json数据,需要把CURLOPT_HTTPHEADER中添加两个头

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
));

 

get如下

function request_get($url = '', $param = '',$header=0) {
        if (empty($url) || empty($param) || empty($header)) {
            return false;
        }
		$i = 0;
        foreach($param as $k=>$v){
			if($i==0){
				$url = $url."?".$k."=".$v;
			}else{
				$url = $url."&".$k."=".$v;
			}
			$i++;
		}
		
        $postUrl = $url;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
		
    }

  

转载于:https://www.cnblogs.com/zonglonglong/p/9626276.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值