Phpcurl encapsulation class

Source: Internet
Author: User
Tags ftp file
The phpcurl encapsulation class is a php curl encapsulation class that reduces the amount of code and simplifies collection. This class is also one of the most common classes for my work. Here we will share with you. It works well with phpquery.

 '', // The requested URL CURLOPT_RETURNTRANSFER => 1, // Set the returned information to be returned in the form of a stream, instead of directly outputting CURLOPT_HTTPGET => 1, // Set the request to GET. // Define the default callback function. in this way, exec () will return 1 CURLOPT_CONNECTTIMEOUT => 30 after the success, // set the default link timeout to 30 seconds CURLOPT_TIMEOUT => 30, // set the maximum download time to 30 seconds. // Automatic tracking and redirection. CURLOPT_FOLLOWLOCATION => true, // Set the client to support gzip compression, which is disabled by default and used to save traffic. CURLOPT_ENCODING => 'gzip', // set the default header CURLOPT_USERAGENT => 'mozilla/5.0 (Windows NT 6.1; rv: 23.0) Gecko/20100101 Firefox/23.0 '); public $ opt; public $ cookieFile = false; // saved COOKIE file/*** cache of http request response, which is cached in the array by default, A maximum of 512 * @ var array */public $ cache = array (); public function _ construct () {// Complete CH initialization $ this-> ch = curl_init (); if (! $ This-> ch) die ('Current environment does not support curl'); $ this-> opt = $ this-> defaultOpt;} // executes the HTTP request, and get the returned data // return the specified matched string. if the matching fails, all documents will be returned. public function exec ($ opt) {// if the query parameter is just a string, it is considered as a url if (! Is_array ($ opt) {$ url = $ opt; $ opt = array (); $ opt ['URL'] = $ url;} // If cache exists, returns the cached string. $ Key = md5 ($ opt ['URL']. $ opt ['post']. $ opt ['match']. $ opt ['Return ']); if ($ str = $ this-> getCache ($ key ))! = False) return $ str; // The current str is cleared before each execution. The Returned values may be different for each request. $ this-> str = ''; // if (! $ This-> setOptions ($ opt) return false; $ flag = curl_exec ($ this-> ch); $ this-> setCache ($ key, $ this-> str? $ This-> str: $ flag); // after the execution is complete, based on the long resident memory and considerations, the last connection option can affect the next build $ this-> opt = $ this-> defaultOpt; if ($ this-> str = '') // The callback function return $ flag; else return $ this-> str;}/*** the simple encapsulated file_get_contents function * is only used for caching. */Public function getContent ($ url) {$ key = md5 ($ url); if ($ str = $ this-> getCache ($ key ))! = False) return $ str; $ str = file_get_contents ($ url); $ this-> setCache ($ key, $ str); return $ str ;} // Set the CURL attribute public function setOptions ($ opt) {foreach ($ opt as $ key => $ value) {// The following values are configurable values. If no, the default value is used. switch ($ key) {case 'URL': // Set the url of the current request $ this-> opt [CURLOPT_URL] = $ value; break; case 'str': // sets the information return method. the default value is 1 $ this-> opt [CURLOPT_RETURNTRANSFER] = $ value; break; // The default value is also 1 case 'method ': // Set the request method. the default value is POST if ($ value = 'get') $ this-> opt [CURLOPT_HTTPGET] = 1; // Set it to GET request elseif ($ value = 'put') $ this-> opt [CURLOPT_PUT] = 1; // ftp file Upload else $ this-> opt [CURLOPT_POST] = 1; break; case 'post ': // Sets the POST request subject in array format. if a file is uploaded, add @ $ this-> opt [CURLOPT_POSTFIELDS] = $ value; break; case 'head' before the file name ': // Set the HEADER request HEADER. it is not used by default. the array format is $ this-> opt [CURLOPT_HTTPHEADER] = $ value; break; case 'referer': // Set the referer information, the default value is null $ this-> opt [CURLOPT_REFERER] = $ value; break; case 'auth': // Set the user password to be requested [username]: [password] $ this-> opt [CURLOPT_USERPWD] = $ value; break; case 'connect _ time': // wait time before initiating a link $ this-> opt [CURLOPT _ CONNECTTIMEOUT] = $ value; break; case 'load _ time': // maximum file download time. $ This-> opt [CURLOPT_TIMEOUT] = $ value; break; case 'callback': // defines the callback function $ this-> opt [CURLOPT_WRITEFUNCTION] = $ value; break; case 'match': // find the regular expression of the specified segment $ this-> opt [CURLOPT_WRITEFUNCTION] = array ('self ', 'callback '); $ this-> match = $ value; case 'proxy': $ this-> opt [CURLOPT_PROXY] = $ value; break; case 'file ': // The filename handle uploaded using FTP $ this-> opt [CURLOPT_VERBOSE] = 1; $ this-> opt [CURLOPT_INFILE] = $ value; // Upload handle $ This-> opt [CURLOPT_NOPROGRESS] = false; $ this-> opt [CURLOPT_FTP_USE_EPRT] = true; $ this-> opt [CURLOPT_FTP_USE_EPSV] = true; break; case 'cookie _ file': // Set the cookie file. $ This-> cookieFile = APP_PATH. '/runtime/cookie.txt'; // send COOKIE $ this-> opt [CURLOPT_COOKIEFILE] = $ this-> cookieFile; // Set cookie $ this-> opt [CURLOPT_COOKIEJAR] = $ this-> cookieFile; break; case 'cookies ': // Set the access cookie to a string $ this-> opt [CURLOPT_COOKIE] = $ value; break; case 'Return ': // Set the returned type if ($ value = 'head') // only the header {$ this-> opt [CURLOPT_NOBODY] = 1 is returned; $ this-> opt [CURLOPT_HEADER] = 1;} elseif ($ Value = 'body') {}// default value, only the body elseif ($ value = 'all') $ this-> opt [CURLOPT_HEADER] = 1 is returned; break; case 'Location': // whether to trace redirection $ this-> opt [CURLOPT_FOLLOWLOCATION] = $ value; break; case 'Client _ type ': // Set the client type $ this-> setClientType ($ value); break; case 'Client _ IP': // Set the client ip address, which is only in the header, not actually forged $ this-> opt [CURLOPT_HTTPHEADER] [] = 'x-FORWARDED-:'. $ value; $ this-> opt [CURLOPT_HTTPHEADER] [] = 'client-IP :'. $ Value; break; }}// sets the current link option. if the option fails to be set, false is returned. return curl_setopt_array ($ this-> ch, $ this-> opt );} // callback function, returns the HTML segment of the specified regular expression public function callback ($ ch, $ str) {$ this-> str. = $ str; preg_match ($ this-> match, $ this-> str, $ match); if (! Empty ($ match) {// if (isset ($ match [1]) $ this-> str = $ match [1]; else $ this-> str = $ match [0]; return false; // Interrupt Request} return strlen ($ str);}/*** get the error message of the current request * @ param int $ type * 0 indicates the error code is obtained, 1 indicates that the error message is obtained, 2 indicates that all information is obtained * @ return mixed */public function getError ($ type = 11) {switch ($ type) {case 0: $ info = curl_errno ($ this-> ch); break; case 1: $ info = curl_error ($ this-> ch); break; defa Ult: $ info = curl_getinfo ($ this-> ch);} return $ info;}/*** clear the cache. */Public function _ destruct () {curl_close ($ this-> ch); $ this-> cache = array () ;}/ *** sets the cache, to reduce the number of http requests. * In a large number of collections, you should rewrite this method. * Memory cache is used by default. * If there are more than 512 cached arrays, clear the array cache. * @ Param string $ key * @ param string $ str * @ return string boolean */public function setCache ($ key, $ str) {if (count ($ this-> cache)> 512) $ this-> cache = array (); $ this-> cache [$ key] = $ str; // if the introduced phpquery object if (class_exists ('\ phpquery') & count (\ phpQuery: $ documents)> 512) \ phpQuery :: $ documents = array ();}/*** get cached data ** @ param string $ key * @ return string boolean */public function getCache ($ key) {If ($ this-> cache [$ key]) return $ this-> cache [$ key]; else return false;}/*** call a remote http interface, returns an array * currently only supports get requests * @ param string $ url * @ param array $ query get query parameters * two of the parameters are custom parameters * _ method: it is the request type * _ type: it is the returned data type. xml and json are supported. * These two parameters do not query strings * @ param array $ type returned format type */public function getArray ($ url, $ query = array ()) {$ method = ($ query ['_ method'] = 'post ')? 'Post': 'get'; $ type = ($ query ['_ type'] = 'xml ')? 'Xml': 'json'; if ($ query ['_ method']) unset ($ query [' _ method']); if ($ query ['_ type']) unset ($ query [' _ type']); if ($ method = 'get') {if ($ query) $ nowUrl = $ url. '? '. Http_build_query ($ query); else $ nowUrl = $ url; $ str = $ this-> exec (array ('URL' => $ nowUrl, 'method' => 'GET',);} else $ str = $ this-> exec (array ('URL' => $ url, 'method' => 'post', 'post' => $ query); if (! $ Str) return false; $ arr = $ this-> toArray ($ str, $ type); if (! $ Arr |! Is_array ($ arr) return false; return $ arr;}/*** converts a {} format javasrcipt object into a php array * to avoid excessive use of regular expressions. * Currently, one-dimensional arrays are supported. * If the js object contains an object. There may be problems. * Generally, you should match only one JS object on the page. * @ Param string $ str * @ return array | bool */public function jsArray ($ str) {$ return = array (); $ str = str_replace (array ('"', "'",' {','} '), '', $ str); $ arr = explode (', ', $ str ); foreach ($ arr as $ row) {$ tmpArr = explode (':', $ row); $ return [trim ($ tmpArr [0])] = trim ($ tmpArr [1]);} return $ return ;} /*** use phpquery to collect html pages * @ param unknown $ str string * @ param string $ query selector expression * @ return \ phpQuery */p Ublic function getDom ($ str, $ query = '') {require_once APP_PATH. '/iphp/extension/phpQuery. php '; $ domObject = \ phpQuery: newDocument ($ str); if ($ query = '') return $ domObject; return pq ($ query );} /*** converts a string into an array. * @ param string $ str string * @ param string $ type. * @ Return array | bool */public function toArray ($ str, $ type = "json") {if ($ type = 'xml ') {$ doc = simplexml_load_string ($ str); $ xml = App: getApp ()-> getXml (); return $ xml-> getTreeArray ($ doc );} elseif ($ type = 'json') return json_decode ($ str, true); elseif ($ type = 'query') {$ parse = parse_url ($ str ); parse_str ($ parse ['query'], $ params); return $ params;} elseif ($ type = 'pathinfo ') {}}/*** default browser client based on type * @ param type $ type * iphone indicates iphone client, * pc indicates pc client, * android indicates android client */public function setClientType ($ type) {$ userAgent = array ('PC' => 'mozilla/5.0 (Windows NT 6.1; rv: 23.0) gecko/20100101 Firefox/23.0 ', 'iPhone' => 'mozilla/5.0 (iPad; U; cpu OS 3_2_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B500 Safari/531.21.10 ', 'Android' => 'mozilla/5.0 (Linux; U; android 2.2; en-us; nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 '); if (array_key_exists ($ type, $ userAgent )) $ this-> opt [CURLOPT_USERAGENT] = $ userAgent [$ type];} // close the current resource connection public function close () {curl_close ($ this-> ch );}}

Example:

 Array ('sdtv', '123', 'Shandong satellite TV '), 1 => array ('qlpd', '123', 'qilu Channel '), 2 => array ('ggpd', '123456', 'public Channel'), 3 => array ('typd', '123456', 'Sports Channel '), 4 => array ('shpd ', '123', 'Life Channel'), 5 => array ('zypd', '123', 'variety Channel '), 6 => array ('nkpd ', '123456', 'agricultural channel'), 7 => array ('yspd ', '123456', 'Video channel '), 8 => array ('sept', '000000', 'Children's Channel'), 9 => array ('gjpd ', '000000', 'International Channel ')/*, 10 => array ('dspd', '000000', 'Reading Channel') */); foreach ($ Lists as $ item) {$ vid = $ item [0]. ','. $ item [1]. ','. $ item [2]; $ channel_name = $ item [2]; $ link = $ this-> getAll ($ vid ); $ this-> info [] = array ('Channel _ name' => $ channel_name, 'Channel _ link' => $ link);} return $ this-> info ;} public function one ($ vid, $ format) {$ arr2 = explode (',', $ vid); if ($ format! = 1) {return false;} $ url =" http://huodong.iqilu.com/active/video/clientnew/public_s/?c= "; $ Str = $ this-> curl-> exec (array ('URL' => $ url. $ arr2 [0], 'header' => array ('host: huodong.iqilu.com ', // 'user-Agent: Android', // "Referer: http://v.iqilu.com/live/ {$ Arr2 [0]}/", 'user-Agent: Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; Coolpad 8675 Build/KOT49H) appleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/9.9.7.500 U3/0.8.0 Mobile Safari/534.30 ',), 'referer' =>" http://m.iqilu.com/vms/live/ {$ Arr2 [0]}/", 'Client _ type' =>" android "); $ arr = explode ('|', $ str); $ vid =" http://m3u8.iqilu.com/live/ $ Arr2 [1]. m3u8? St = ". $ arr [16]. $ arr [17]. "& e = ". $ arr [19]. $ arr [20]; // & e = {$ arr [17]}; return $ vid ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.