PHP Curl wrapper class

Source: Internet
Author: User
Tags ftp file set cookie
A PHP curl encapsulated class that reduces the amount of code and simplifies the collection effort. This class is also one of the most commonly used classes for my work. Here to share with you. With the phpquery, very useful.

  ',//request URL Curlopt_returntransfer = 1,//set to return information in the form of a stream, not directly output Curlopt_httpget = 1,//set to get        Request. Define the default callback function so that exec () returns 1 curlopt_connecttimeout = 30 after success,//Set default link timeout to 30 seconds curlopt_timeout=>30,//set        Load time up to 30 seconds.        Auto-trace redirection.        Curlopt_followlocation = True,//Set the client supports gzip compression, which is not turned on by default and is used to save traffic.  curlopt_encoding = ' gzip ',//Set Default header 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/** * HTTP request response cache, default cache in array, maximum 512 * @var array */Public $cache = Array ();        Public Function __construct () {//completion of the initialization of ch $this->ch = Curl_init ();        if (! $this->ch) Die (' The current environment does not support curl ');    $this->opt= $this->defaultopt; }//execute HTTP request and get Return data//return specified matched string, if match failure will return all documents Public function exec ($opt) {//If the parameter is just a string,Considered to be a URL if (!is_array ($opt)) {$url = $opt;            $opt =array ();        $opt [' url ']= $url;        }//If there is a cache, the cached string is returned.        $key = MD5 ($opt [' url ']. $opt [' Post ']. $opt [' Match ']. $opt [' return ']);            if ($str = $this->getcache ($key))! = false) return $str;        Before each execution, empty the current STR, each request, the return value may not be the same $this->str = ";        Parameter settings fail and execution line failure will return fasle;        if (! $this->setoptions ($opt)) return false;        $flag = curl_exec ($this->ch);                $this->setcache ($key, $this->str? $this->str: $flag);                After execution, based on long-standing memory and considerations, the last connection option can affect the next $this->opt= $this->defaultopt;        if ($this->str = = ")//indicates that no callback function is executed for return $flag;    else return $this->str;     }/** * Simply encapsulates the file_get_contents function * just using the cache.        */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 Curl Property Public Function setoptions ($opt) {foreach ($opt as $key = = $value) {//the following values are The value that can be set. If not, the default value will be used; switch ($key) {case ' URL '://sets the URL of the current request $this->opt[curlopt_                    URL] = $value;                Break                    Case ' str '://Set information return mode, default to 1 $this->opt[curlopt_returntransfer] = $value; Break The default value is also 1 case ' method '://Set request mode, default to post if ($value = = ' Get ') $ This->opt[curlopt_httpget] = 1; Set to get request ElseIf ($value = = ' put ') $this->opt[curlopt_put] = 1;                    FTP file Upload else $this->opt[curlopt_post] = 1;                Break Case ' post '://Set POST request body, array form, if upload file, the file name plus @ $this->opt[curlopt_postfields] = $value;                Break                    Case ' header '://Set Header request header, default not used, array form $this->opt[curlopt_httpheader] = $value;                Break                    Case ' referer '://Set Referer information, default is empty $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 the link $this->opt[curlopt_connecttimeout] = $value;                Break                    Case ' load_time '://File download for the longest time.                    $this->opt[curlopt_timeout]= $value;                Break                    Case ' callback '://define callback function $this->opt[curlopt_writefunction] = $value;                Break Case ' match '://Find the regular expression for the specified segment $thiS->opt[curlopt_writefunction] = Array (' Self ', ' callback '                    );                $this->match = $value;                    Case ' proxy ': $this->opt[curlopt_proxy] = $value;                Break                    Case ' file '://File name with FTP upload $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 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 ' cookie '://Set access cookie to a string $this->opt[curlopt_cookie]= $value;                Break                        Case ' return '://sets the return type if ($value = = ' head ')//indicates only the header {                        $this->opt[curlopt_nobody] = 1;                    $this->opt[curlopt_header] = 1;                        } elseif ($value = = ' body ') {}//default value, return only body body elseif ($value = = ' All ')                    $this->opt[curlopt_header] = 1;                Break                    Case ' location '://IS not tracking redirect $this->opt[curlopt_followlocation]= $value;                Break                    Case ' client_type '://Set Client type $this->setclienttype ($value);                Break Case ' client_ip '://Set client IP address, just in header, not real forged $this->opt[curlopt_httpheader][]= ' x-forwarded-For: '. $value;                    $this->opt[curlopt_httpheader][]= ' client-ip: ' $value;            Break        }}//Set the current Link option, option settings failed to return false;    Return Curl_setopt_array ($this->ch, $this->opt);        }//callback function that 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)) {//There is a sub-pattern, return this sub-mode if (Isset ($match [1])) $this->st            r = $match [1];            else $this->str = $match [0]; return false;    Interrupt Request} return strlen ($STR); }/** * Gets the error message for the current request * @param int $type * 0 for error encoding, 1 for error message, 2 for all information * @return Mixed */publi C function GetError ($type = one) {switch ($type) {case 0: $info = Curl_errno ($this-&                GT;CH);            Break Case 1: $info = curl_erRor ($this->ch);            Break        Default: $info = Curl_getinfo ($this->ch);    } return $info;     }/** * clears the cache.        */Public Function __destruct () {curl_close ($this->ch);    $this->cache = Array ();     }/** * Set the cache to reduce the number of HTTP requests.     * In bulk collection, you should use override this method instead.     * Memory cache will be used by default * if the cache array exceeds 512, the array cache is emptied. * @param string $key * @param string $str * @return String Boolean */Public functi        On Setcache ($key, $str) {if (count ($this->cache) >512) $this->cache=array ();                $this->cache[$key] = $str; If the Phpquery object is introduced if (class_exists (' \\phpQuery ') && count (\phpquery:: $documents) >512) \phpquer    Y:: $documents =array (); }/** * Get Cached Data * * @param string $key * @return String Boolean */Public function G           Etcache ($key) {if ($this->cache[$key]) return $this->cache[$key];    else return false; /** * calls the remote HTTP interface, returns an array * currently only supports GET requests * @param string $url * @param array $query get mode query parameter * two parameters     Number of custom parameters * _method: For the requested type * _type: For the returned data type, supports Xml,json. * These two parameters do not make a query string * @param array $type return format type */Public function GetArray ($url, $query =array ()) {$metho d= ($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 (the ' url ' = ' + $url, ' method ' = ' post ', ' post ' =    > $query)); if (! $str) returnfalse; $arr = $this->toarray ($str, $type), if (! $arr | |!is_array ($ARR)) return False;return $arr;     /** * Convert a {} Javasrcipt object into a PHP array * To avoid excessive use of regular expressions. * currently supports one-dimensional arrays; * If JS has an object inside the image.     There may be a problem.     * Normally, you should only match a JS object in the page.    * @param string $str * @return Array|bool */Public Function Jsarray ($str) {$return =array ();    $str =str_replace (' "'," ' ", ' {', '} '), ', $str);    $arr =explode (', ', $str);    foreach ($arr as $row) {$tmpArr =explode (': ', $row);    $return [Trim ($tmpArr [0])]=trim ($TMPARR [1]);    } return $return; }/** * use Phpquery for HTML page capture * @param unknown $str String * @param string $query selector expression * @return \phpque RY */Public Function getdom ($str, $query = ") {require_once app_path. '        /iphp/extension/phpquery/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 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 ') {}}/** * According to type default browser client * @param type    $type * iphone represents iphone client, * PC represents PC client Client, * Android represents android client */Public function Setclienttype ($type) {$userAgent =array (' pc ' = ' mozilla/5.0 (Windows NT 6.1; rv:23.0) gecko/20100101 firefox/23.0 ', ' iph One ' = ' 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 ' = ' Mozil ' la/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 current resource connection public function close () {curl_close ($this->ch); }}

Examples of Use:

  Array (' SDTV ', ' 98/0 ', ' Shandong satellite TV '), 1 = = Array (' QLPD ', ' 98/1 ', ' Qilu Channel '), 2 = = Array (' GGPD ', ' 98/2 ', ' public Channel '), 3 = Array ( ' Typd ', ' 98/3 ', ' Sports Channel '), 4 = = Array (' SHPD ', ' 99/2 ', ' Life Channel '), 5 = = Array (' ZYPD ', ' 100/0 ', ' Art Channel '), 6 = Array (' NKPD ', ' 99/0 ', ' Agriculture Channel '), 7 = = Array (' yspd ', ' 99/3 ', ' Movie Channel '), 8 = = Array (' SEPD ', ' 99/1 ', ' Children's Channel '), 9 = = Array (' GJPD ', ' 100/1 ', ' International channel ')/*,10 = = Array (' dspd ', ' 107/6 ', ' 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 ' = = $cha Nnel_name, ' channel_link ' = $link);} return $this->info;} Public function One ($vid, $format) {$arr 2 = 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. $arr 2 [0], ' header ' = = Array (' Host:huodong.iqilu.com ',//' user-agent:android ',//' Referer:http://v.iqilu.com/live/{$arr 2[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/{$arr 2[0]}/', ' client_type ' = ' Android '); $arr = Explode (' $STR) $vid = "http://m3u8.iqilu.com/live/$arr 2[1].m3u8?st=" $arr [+]. $arr [17]. " &e= ". $arr []. $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.