工作中第一次用到header做个记录
工作中需要在heaer里面加上
Authorization 用来验证身份
public function index()
{
$url = "http://te33333.com";
$param['username'] = "uduje";
$param['password'] = "";
$header[] = "Authorization:Basic ZWNjbGllbnQ6ZWXQ=";//我已开始把authorization写到了key里面就出错了
$result = $this->request_post($url,$param,$header);
dump($result);
//$this->display();
}
public function request_post($url = '', $param = '',$header=) {
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, );//设置header输出,0不输出1输出
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header输入
curl_setopt($ch, CURLOPT_RETURNTRANSFER, );//要求结果为字符串且输出到屏幕上,0输出1不输出
curl_setopt($ch, CURLOPT_POST, );//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; }