PHP中使用CURL实现GET和POST请求(转载)

时间:2022-06-24 21:31:50

CURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 CURL 库。使用PHP的CURL 库可以简单和有效地去抓网页。你只需要运行一个脚本,然后分析一下你所抓取的网页,然后就可以以程序的方式得到你想要的数据了。无论是你想从从一个链接上取部分数据,或是取一个XML文件并把其导入数据库,那怕就是简单的获取网页内容,CURL 是一个功能强大的PHP库。

PHP建立CURL请求的基本步骤

①:初始化

curl_init()

②:设置属性

curl_setopt().有一长串CURL 参数可供设置,它们能指定URL请求的各个细节。

③:执行并获取结果

curl_exec()

④:释放句柄

curl_close()

CURL实现GET和POST

①:GET方式实现

 //初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com');
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, );
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, );
//执行命令
$data = curl_exec($curl);
//关闭URL请求
curl_close($curl);
//显示获得的数据
print_r($data);

②:POST方式实现

 //初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com');
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, );
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, );
//设置post方式提交
curl_setopt($curl, CURLOPT_POST, );
//设置post数据
$post_data = array(
"username" => "coder",
"password" => ""
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
//执行命令
$data = curl_exec($curl);
//关闭URL请求
curl_close($curl);
//显示获得的数据
print_r($data);

③:如果获得的数据时json格式的,使用json_decode函数解释成数组。

$output_array = json_decode($data,true); //如果第二个参数为true,就转为数组的形式。如果不填就为对象的形式

如果使用json_decode($data)解析的话,将会得到object类型的数据。

我自己封装的一个函数

 //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
function curl_request($url,$post='',$cookie='', $returnCookie=){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, );
curl_setopt($curl, CURLOPT_AUTOREFERER, );
curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
if($post) {
curl_setopt($curl, CURLOPT_POST, );
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
}
if($cookie) {
curl_setopt($curl, CURLOPT_COOKIE, $cookie);
}
curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
curl_setopt($curl, CURLOPT_TIMEOUT, );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, );
$data = curl_exec($curl);
if (curl_errno($curl)) {
return curl_error($curl);
}
curl_close($curl);
if($returnCookie){
list($header, $body) = explode("\r\n\r\n", $data, );
preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
$info['cookie'] = substr($matches[][], );
$info['content'] = $body;
return $info;
}else{
return $data;
}
}

这俩个函数虽然不难,但是还是值得学习一下的。因为在做接口或者调用的接口的时候,必定会用到这俩个函数。