php之curl操作

php之curl操作
1、curl发送cookie以及header头信息实例

<?php
header('Content-Type: text/html; charset=utf-8');

$cookie_file = dirname(__FILE__).'/cookie.txt'; //定义cookie存放的文件

//先获取cookies并保存
$url = "localhost/curl/index.php";
$ch = curl_init($url); //初始化
curl_setopt($ch, CURLOPT_HEADER, 0); //curl_exec($ch)获取到的字符串 不显示header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而非直接输出
curl_setopt($ch, CURLOPT_NOBODY,true); //curl_exec($ch)获取到的字符串 不显示body 这一句要不要都可以
curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file); //将cookies存放在$cookie_file文件中
curl_exec($ch);
curl_close($ch);



//定义header头信息,可以包含任意头信息,包括获自己去网上取到的cookie值
$opts = array( 
"X-Requested-With: XMLHttpRequest", //如果客服端是AJAX请求 的  用户可能在服务器端 判断 => "X-Requested-With: XMLHttpRequest"
          "Accept: */*",
"Referer: http://localhost",
"Accept-Language: zh-CN",
"Accept-Encoding: gzip, deflate",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko",
"Connection: Keep-Alive",
"Cookie:Hm_lvt_c87d2a784e2857c943081ae51392218e=1646343732,1554675736; PHPSESSID=ci0usur7u0197kp30vmn1li233"
);


//使用上面保存的cookies再次访问
$url = "localhost/curl/index.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0); //curl_exec($ch)获取到的字符串 不显示header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //使用上面获取的cookies
curl_setopt($ch,CURLOPT_HTTPHEADER,$opts); //再加上一些header头信息
$response = curl_exec($ch);
curl_close($ch);
echo $response;


2、curl发送post请求实例

<?php
header('Content-Type: text/html; charset=utf-8');


$url = 'localhost/curl/index.php';
$datas = array(
'name' => '哈哈', 
'pass' => 'hello'
);
if(is_array($datas)) $datas = http_build_query($datas); //生成 URL-encode 之后的请求字符串
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
$response = curl_exec($ch);
echo $response;

3、curl发送get请求实例

$url = 'localhost/curl/index.php';
$datas = array(
'name' => '哈哈', 
'pass' => 'hello'
);
if(empty($url) || empty($datas))return false;
if(is_array($datas))$datas=http_build_query($datas); 
$url=$url.'?'.$datas;
$ch=curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$response=curl_exec($ch);
curl_close($ch);
echo $response;

4、发送https请求

当请求https的数据时,会要求证书,这时候,加上下面这两个参数,规避ssl的证书检查

代码如下:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值