php使用cUrl方法 get、post请求

php使用curl方法,请确保已经开启curl扩展。传送门:http://www.cnblogs.com/wgq123/p/7450667.html

/**Curl请求get方法
*@$url String 要请求的url地址
*@$dara Array 要传递的参数
*@$timeout int 超时时间
*@return json
/
function
curlGetRequest($url='', $data=array(), $timeout=5){ if($url == '' || $timeout <=0){ return false; } $param = ''; if(!empty($data)){ foreach($data as $k=>$v){ $param .= $k . '=' . $v .'&'; } $param = rtrim($param, '&'); $url = $url.'?'.$param; } $con = curl_init(); curl_setopt($con, CURLOPT_URL, $url); curl_setopt($con, CURLOPT_HEADER, false); curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
   curl_setopt($con, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); curl_setopt(
$con, CURLOPT_TIMEOUT, (int)$timeout); $output = curl_exec($con); curl_close($con); return $output; }

/**Curl请求Post方法
*@$url String 要请求的url地址
*@$dara Array 要传递的参数
*@$timeout int 超时时间
*@return json
/
function curlPostRequest($url='', $data=array(), $timeout=5){
  
if($url == '' || empty($data) || $timeout <=0){
    
return false;
  }

  $param = '';
  foreach($data as $k=>$v){
    
$param .= $k . '=' . $v .'&';
  }
  $param = rtrim($param, '&');

  $con = curl_init();
  curl_setopt(
$con, CURLOPT_URL, $url);
  curl_setopt(
$con, CURLOPT_HEADER, false);
  curl_setopt(
$con, CURLOPT_POSTFIELDS, $param);
  curl_setopt(
$con, CURLOPT_POST,true); curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
  curl_setopt($con, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  curl_setopt(
$con, CURLOPT_TIMEOUT,(int)$timeout);
  $output = curl_exec($con);
  curl_close(
$con);

  return $output;
}

 

$url="http://127.0.0.1/request.php";
$timeout = 5;
$data = array('name'=>'张三','password'=>'123');

$res1 =curlGetRequest($url,$data);
$res2 =curlPostRequest($url,$data);
echo $res2;

 

参考链接: http://www.cnblogs.com/manongxiaobing/p/4698990.html

                  http://www.thinkphp.cn/code/1612.html

posted @ 2017-08-31 12:03  向北☆  阅读(711)  评论(0编辑  收藏  举报