php实现的Curl封装类Curl.class.php用法实例分析
程序员文章站
2022-05-18 12:58:57
本文实例讲述了php实现的curl封装类curl.class.php用法。分享给大家供大家参考。具体如下:
本文实例讲述了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程序设计有所帮助。
上一篇: PHP中的Session对象如何使用
下一篇: UBB编辑器