CURL模拟HTTP请求

时间:2021-10-15 16:57:50
/**
* CURL模拟HTTP请求
* @param string $url
* @param string $type
* @param array $data
* @return array|boolean
*/
function curlData($url, $type = 'GET', $data = array()){
$ch = curl_init();
if(empty($url) || ! $ch) return false;
if(strtoupper($type) == 'POST'){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}else{
$url .= '?' . http_build_query($data);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
//$err_no = curl_errno($ch);
//$err_info = curl_getinfo($ch);
curl_close($ch);
return $result;
}

  1. /** 
  2.  *  
  3.  * @param $url 
  4.  * @param $data 
  5.  * @param $method 
  6.  */  
  7. function curlrequest($url,$data,$method='post'){  
  8.     $ch = curl_init(); //初始化CURL句柄   
  9.     curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL  
  10.     curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出   
  11.     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式  
  12.       
  13.     curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: $method"));//设置HTTP头信息  
  14.     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串  
  15.     $document = curl_exec($ch);//执行预定义的CURL   
  16.   
  17.     curl_close($ch);  
  18.       
  19.     return $document;  
  20. }  
  21.   
  22. $url = 'www.wxh.com/3.php';  
  23. $data = "m=1&c=2&jaingxi=67";  
  24. $return = curlrequest($url, $data, 'put');  
  25. var_dump($return);
/**
* Func 生成短URL
* @param string $url 源路径地址
* @param int $type 1-7 生成短url的域名 2是t.cn
*/
function GetShortUrl ($url,$type = 2){
$path = 'http://www.ft12.com/create.php?m=index&a=urlCreate';//生成短连接网站
$data['url'] = $url;
$data['type'] = $type;
$content = curlData($path,'post' , $data);
if($content){
$result = json_decode($content, true);
if($result['status'] == 1){
return $result['list'];
}else{
return false;
}
}
}