PHP-curl implements GET or POST requests
It is easy to obtain target website data through Curl
Supported protocols: Http, Https
A form can be attached according to specific needs , cookies.
GET request:
/** * curl模拟get进行 http 或 https url请求(可选附带cookie) * @parambool $type请求类型:true为https请求,false为http请求 * @paramstring $url请求地址 * @paramstring$cookie cookie字符串 * @returnstring返回字符串 */ function curl_get($type, $url, $cookie) {//type与url为必传、若无cookie则传空字符串 if (empty($url)) { return false; } $ch = curl_init();//初始化curl curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 if($type){ //判断请求协议http或https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在 } curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 if(!empty($cookie))curl_setopt($ch,CURLOPT_COOKIE,$cookie); //设置cookie $data = curl_exec($ch);//运行curl curl_close($ch); return $data; }
POST request:
/** * curl模拟post进行 http 或 https url请求(可选携带表单,cookie) * @parambool $type请求类型:true为https请求,false为http请求 * @paramstring$url请求地址 * @paramarray $post_data请求表单数据array("key1"=>"value1","key2"=>"value2"),表单以数组方式传输 * @paramstring$cookiecookie字符串 * @returnstring返回字符串 */ function curl_post($type, $url, $post_data, $cookie) {//type与url为必传 ,表单post_data数组,和cookie字符串选传 if (empty($url)) { return false; } if(!empty($post_data)){ $params = ''; foreach ( $post_data as $k => $v ) { $params.= "$k=" . urlencode($v). "&" ; } $params = substr($params,0,-1); } $ch = curl_init();//初始化curl curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 if($type){ //判断请求协议http或https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在 } curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 if(!empty($cookie))curl_setopt($ch,CURLOPT_COOKIE,$cookie); //设置cookie if(!empty($post_data))curl_setopt($ch, CURLOPT_POSTFIELDS, $params); //设置表单 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 $data = curl_exec($ch);//运行curl curl_close($ch); return $data; }
Recommended: "PHP Tutorial"
The above is the detailed content of PHP-curl implements http and https requests through GET or POST. For more information, please follow other related articles on the PHP Chinese website!