使用 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
这是一段来自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则有
当然,设置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);
?>
输出结果为