当前位置:   article > 正文

PHP-curl通过GET或POST方式实现http、https请求_php curl get请求http

php curl get请求http

PHP-curl实现GET或POST请求

通过Curl方式很容易获取目标网站数据
支持协议:Http、Https
可根据具体需求附带表单、cookie。

GET请求:
/**
 * curl模拟get进行 http 或 https url请求(可选附带cookie) 
 * @param	string $url	请求地址
 * @param	string	$cookie cookie字符串
 * @return	string	返回字符串
 */
function curl_get($url, $cookie) {//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(strpos($url, 'https://')!== false){  //判断请求协议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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
POST请求:
/**
 * curl模拟post进行 http 或 https url请求(可选携带表单,cookie)
 * @param	string	$url	请求地址
 * @param	array 	$post_data	请求表单数据array("key1"=>"value1","key2"=>"value2"),表单以数组方式传输
 * @param	string	$cookie	cookie字符串 
 * @return	string	返回字符串
 */
function curl_post($url, $post_data, $cookie) {//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(strpos($url, 'https://')!== false){  //判断请求协议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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号