curl常用操作之get,post,cookie,file

使用 cURL 函数的基本思想是先使用 curl_init() 初始化 cURL会话,接着可以通过 curl_setopt() 设置需要的全部选项,然后使用 curl_exec() 来执行会话,当执行完会话后使用 curl_close() 关闭会话。

get抓取页面内容

<?php
$ch = curl_init()
$options = array(
    CURLOPT_URL => 'http://www.baidu.com',
    CURLOPT_RETURNTRANSFER => TRUE,  //设置返回结果以字符串输出,否则直接输出
    CURLOPT_HEADER => 0
);
curl_setopt_array($ch, $options);
$out = curl_exec($ch);
curl_close($ch);
file_put_contents('./baidu.html', $out);
?>

如果需要直接写入文件,还可以用另外一种方式

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'www.baidu.com');
$fp = fopen('./baidu.html', 'w');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>

值得注意的是,CURLOPT_RETURNTRANSFER一定要写在CURLOPT_FILE前面,否则无法写入

http的POST实现

<?php
$url = 'http://localhost/test.php';
$postdata = array(
    'name'  => 'rainn',
    'age'   => '25',
    'job'   => 'programmer',
    'hobby' => 'singing'
);
$ch = curl_init();
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_POST => 1, // 启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded  
    CURLOPT_POSTFIELDS => $postdata  //在HTTP中的“POST”操作。如果要传送一个文件,需要一个@开头的文件名
);
curl_setopt_array($ch, $options);
$out = curl_exec($ch);
curl_close($ch);
var_dump($out);
?>

curl设置cookie

135518_DcfD_2667773.png

这是一段来自qq邮件的http请求的cookie信息,看的出来,不同信息之间使用;而不是&隔开的,所以我们在写cookie信息的时候也需要这么写,假设我需要访问的信息中需要uid,pwd,那么则需要这么操作

<?php
$ch = curl_init();
$url = 'http://localhost/test.php';
$cookie = array(
	'uid'   => 1,
	'pwd'   => md5('password'),
	'token' => str_shuffle((string)time()).md5(time())
);
$setCookie = http_build_query($cookie, '', ';');
$options = array(
	CURLOPT_URL => $url,
	CURLOPT_RETURNTRANSFER => 1,
	CURLOPT_HEADER => 0,
	CURLOPT_COOKIE => $setCookie
);
curl_setopt_array($ch, $options);
$out = curl_exec($ch);
curl_close($ch);
var_export($out);
?>

在test.php中打印$_COOKIE则有

141444_3dvi_2667773.png

当然,设置cookie也可以直接在header中设置

cURLFile的使用

<?php
$ch = curl_init();
$url = 'http://localhost/index.php';
$file = new CURLFile('./pic.jpg','image/jpg', 'test.pic');
// $file = curl_file_create('./pic.jpg','image/jpg', 'testpic');
$post = array(
	'name'=>'rainn',
	'test'=>$file
);
$options = array(
	CURLOPT_URL => $url,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_POST => true,
	CURLOPT_POSTFIELDS => $post
);
curl_setopt_array($ch, $options);
$out = curl_exec($ch);
curl_close($ch);
var_export($out);
?>

输出结果为

144034_F2q5_2667773.png

转载于:https://my.oschina.net/OSrainn/blog/724015

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值