php之curl操作

来源:互联网 发布:淘宝美工与平面设计 编辑:程序博客网 时间:2024/05/29 12:58
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
原创粉丝点击