当前位置: 移动技术网 > IT编程>开发语言>PHP > php访问url(get和post请求)

php访问url(get和post请求)

2018年09月07日  | 移动技术网IT编程  | 我要评论

 

  • get请求

 

/*
* php访问url路径,get请求
*/
function curl_file_get_contents($durl){
// header传送格式
$headers = array(
"token:1111111111111",
"over_time:22222222222",
);
// 初始化
$curl = curl_init();
// 设置url路径
curl_setopt($curl, curlopt_url, $durl);
// 将 curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, curlopt_returntransfer, true) ;
// 在启用 curlopt_returntransfer 时候将获取数据返回
curl_setopt($curl, curlopt_binarytransfer, true) ;
// 添加头信息
curl_setopt($curl, curlopt_httpheader, $headers);
// curlinfo_header_out选项可以拿到请求头信息
curl_setopt($curl, curlinfo_header_out, true);
// 执行
$data = curl_exec($curl);
// 打印请求头信息
// echo curl_getinfo($curl, curlinfo_header_out);
// 关闭连接
curl_close($curl);
// 返回数据
return $data;
}

 

 

  • post请求

/*
* php访问url路径,post请求
*
* durl 路径url
* post_data array() post参数数据
*/
public function curl_file_post_contents($durl, $post_data){
// header传送格式
$headers = array(
"token:1111111111111",
"over_time:22222222222",
);
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, curlopt_url, $durl);
//设置头文件的信息作为数据流输出
curl_setopt($curl, curlopt_header, false);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, curlopt_returntransfer, true);
//设置post方式提交
curl_setopt($curl, curlopt_post, true);
// 设置post请求参数
curl_setopt($curl, curlopt_postfields, $post_data);
// curlinfo_header_out选项可以拿到请求头信息
curl_setopt($curl, curlinfo_header_out, true);
//执行命令
$data = curl_exec($curl);
// 打印请求头信息
// echo curl_getinfo($curl, curlinfo_header_out);
//关闭url请求
curl_close($curl);
//显示获得的数据
return $data;
}

 

注:调用后可以通过json_decode来解析返回结果:如:
$data= $this->curl_file_post_contents($dataurl, $post_data);
$dataarr = json_decode($data, true);
 
 
 
 
 
 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网