当前位置: 移动技术网 > IT编程>开发语言>PHP > php实现的Curl封装类Curl.class.php用法实例分析

php实现的Curl封装类Curl.class.php用法实例分析

2018年05月02日  | 移动技术网IT编程  | 我要评论
本文实例讲述了php实现的curl封装类curl.class.php用法。分享给大家供大家参考。具体如下: <?php //curl类 clas

本文实例讲述了php实现的curl封装类curl.class.php用法。分享给大家供大家参考。具体如下:

<?php
//curl类
class curl
{
 function curl(){
  return true;
 }
 function execute($method, $url, $fields='', $useragent='', $httpheaders='', $username='', $password=''){
  $ch = curl::create();
  if(false === $ch){
   return false;
  }
  if(is_string($url) && strlen($url)){
   $ret = curl_setopt($ch, curlopt_url, $url);
  }else{
   return false;
  }
  //是否显示头部信息
  curl_setopt($ch, curlopt_header, false);
  //
  curl_setopt($ch, curlopt_returntransfer, true);
  if($username != ''){
   curl_setopt($ch, curlopt_userpwd, $username . ':' . $password);
  }
  $method = strtolower($method);
  if('post' == $method){
   curl_setopt($ch, curlopt_post, true);
   if(is_array($fields)){
    $sets = array();
    foreach ($fields as $key => $val){
     $sets[] = $key . '=' . urlencode($val);
    }
    $fields = implode('&',$sets);
   }
   curl_setopt($ch, curlopt_postfields, $fields);
  }else if('put' == $method){
   curl_setopt($ch, curlopt_put, true);
  }
  //curl_setopt($ch, curlopt_progress, true);
  //curl_setopt($ch, curlopt_verbose, true);
  //curl_setopt($ch, curlopt_mute, false);
  curl_setopt($ch, curlopt_timeout, 10);//设置curl超时秒数
  if(strlen($useragent)){
   curl_setopt($ch, curlopt_useragent, $useragent);
  }
  if(is_array($httpheaders)){
   curl_setopt($ch, curlopt_httpheader, $httpheaders);
  }
  $ret = curl_exec($ch);
  if(curl_errno($ch)){
   curl_close($ch);
   return array(curl_error($ch), curl_errno($ch));
  }else{
   curl_close($ch);
   if(!is_string($ret) || !strlen($ret)){
    return false;
   }
   return $ret;
  }
 }
 function post($url, $fields, $useragent = '', $httpheaders = '', $username = '', $password = ''){
  $ret = curl::execute('post', $url, $fields, $useragent, $httpheaders, $username, $password);
  if(false === $ret){
   return false;
  }
  if(is_array($ret)){
   return false;
  }
  return $ret;
 }
 function get($url, $useragent = '', $httpheaders = '', $username = '', $password = ''){
  $ret = curl::execute('get', $url, '', $useragent, $httpheaders, $username, $password);
  if(false === $ret){
   return false;
  }
  if(is_array($ret)){
   return false;
  }
  return $ret;
 }
 function create(){
  $ch = null;
  if(!function_exists('curl_init')){
   return false;
  }
  $ch = curl_init();
  if(!is_resource($ch)){
   return false;
  }
  return $ch;
 }
}
?>

get用法:

$curl = new curl();
$curl->get('http://www.xxx.com/');

post用法:

$curl = new curl();
$curl->get('http://www.xxx.com/', 'p=1&time=0');

希望本文所述对大家的php程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网