Examples of httpclient class usages in PHP encapsulation

Source: Internet
Author: User
Tags header http request php programming preg socket strlen first row trim

This example describes the HttpClient class in PHP encapsulation. Share to everyone for your reference. The specific analysis is as follows:

This is a PHP-encapsulated HttpClient class that enables simple functions such as Get POST Cookie sessions. Originally done, the two days have been modified a bit.

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140-1 41 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170-171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201-2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231-232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 <?php/* Filename:httpclient.php * Created on 2012-12-21 * Created with Robintang * To change the template for this G enerated file Go to * window-preferences-phpeclipse-php-code Templates */class Sincookie {public $name;//Cooki e name public $value; Cookie value//The following three properties do not now implement public $expires; The expiration time is public $path; Path public $domain; Domain//Create a cookie object from the cookie string function __construct ($s = false) {if ($s) {$i 1 = strpos ($s, ' = '); $i 2 = Strpos ($s, '; '); $this->name = Trim (substr ($s, 0, $i 1)); $this->value = Trim (substr ($s, $i 1 +1, $i 2-$i 1-1)); }//Get cookie Key value pair function Getkeyvalue () {return "$this->name= $this->value";}} Session Context class Sinhttpcontext {public $cookies;//session cookies public $referer;//Previous page address function __construct () {$this-& gt;cookies = Array (); $this->refrer = "";} Set Cookie function Cookie ($key, $val) {$ck = new Sincookie (); $ck->name = $key; $ck->value = $val; $this->ADDC Ookie ($CK); }//Add Cookie function Addcookie ($CK) {$this->cookies[$ck->name] = $ck}//Get a cookie string, use the function cookiesstring () {$res = '; foreach ($this-& Gt;cookies as $ck) {$res. = $ck->getkeyvalue (). ';'; return $res; }//HTTP Request object class Sinhttprequest {public $url;//Request address public $method = ' get ';//request method public $host;//Host public $PA Th Path public $scheme; Protocol, HTTP public $port; Port public $header; Request head public $body; Request Body//Set Header function SetHeader ($k, $v) {if (!isset ($this->header)) {$this->header = array ();} $this->head er[$k] = $v; //Get request string//Include header and request body//fetch directly after write socket on line function reqstring () {$matches = Parse_url ($this->url);!isset ($matches [' Host '] && $matches [' host '] = ';!isset ($matches [' path ']) && $matches [' path '] = ';!isset ($matches [' Qu Ery '] && $matches [' query '] = ';!isset ($matches [' Port ']) && $matches [' port '] = '; $host = $matches [' Host ']; $path = $matches [' Path ']? $matches [' Path ']. ($matches [' query ']? '?' . $matches [' Query ']: ': '/'; $port =!empty ($matches [' Port '])? $matches [' Port ']: 80; $scheme = $matches [' scheme ']? $matches [' scheme ']: ' http '; $this->host = $host; $this->path = $path; $this->scheme = $scheme; $this->port = $port; $method = Strtoupper ($this->method); $res = "$method $path http/1.1rn"; $res. = "Host: $hostrn"; if ($this->header) {reset ($this->header); while (the list ($k, $v) = each ($this->header)) {if (Isset ($v) &&amp ; strlen ($v) > 0) $res. = "$k: $vrn"; }} $res. = "RN"; if ($this->body) {$res. = $this->body; $res. = "Rnrn";} return $res; }///HTTP response class Sinhttpresponse {public $scheme;//protocol public $stasus;//Status, success is OK public $code;//Status Code, success is 200 Public $header; Response Head public $body; Response body Function __construct () {$this->header = array (); $this->body = null;} function SetHeader ($key, $val) {$t his->header[$key] = $val; }//HttpClient class Sinhttpclient {public $keepcontext = true;//whether to maintain session public $context Context public $request; Request public $response; Response public $debug = false; Whether the request content is printed and the same header function __construct () {$this->request = new Sinhttprequest () in debug mode, or True); $this-> Response = new Sinhttpresponse (); $this->context = new Sinhttpcontext (); $this->timeout = 15; The default timeout is 15s}//clear the Last Request Content function clearrequest () {$this->request->body = '; $this->request->setheader (' Content-length ', false); $this->request->setheader (' Content-type ', false); }///Post method//data for the requested date//as the key value pair when the simulation form submission//other time for the data submission, submitted in the form of XML//If there are other requirements, please extend the function post ($url, $data = False) {$th Is->clearrequest (); if ($data) {if (Is_array ($data)) {$con = Http_build_query ($data); $this->request->setheader (' Content-type ', ' Application/x-www-form-urlencoded '); else {$con = $data; $this->request->setheader (' Content-type ', ' text/xml; Charset=utf-8 ');} $this->request-& Gt;body = $con; $this->request->method = "POST"; $this->request->sethEader (' Content-length ', strlen ($con)); $this->startrequest ($url); }//Get Method function Get ($url) {$this->clearrequest () $this->request->method = ' get '; $this->startrequest ($ URL); The method is called internally, without directly calling function Startrequest ($url) {$this->request->url = $url; if ($this->keepcontext) {//If guaranteed Setting relevant information $this->request->setheader (' Referer ', $this->context->refrer); $cks = $this->context->cookiesstring (); if (strlen ($cks) > 0) $this->request->setheader (' Cookie ', $cks); //Get the request content $reqstring = $this->request->reqstring (); if ($this->debug) echo "REQUEST:N$REQSTRINGN"; try {$fp = Fsockopen ($this->request->host, $this->request->port, $errno, $errstr, $this->timeout); catch (Exception $ex) {echo $ex->getmessage (); exit (0);} if ($fp) {stream_set_blocking ($fp, true); Stream_set_timeo UT ($fp, $this->timeout); Write Data fwrite ($FP, $reqstring); $status = Stream_get_meta_data ($FP); if (! $status [' timed_out ']) { No timeout//The following loops are used to read the response head while (!feof ($fp)) {$h = Fgets ($FP); if ($this->debug) echo $h; if ($h && ($h = "RN" || $h = = = "n")) break; $pos = Strpos ($h, ': '); if ($pos) {$k = Strtolower (Trim (substr ($h, 0, $pos)); $v = Trim (substr ($h, $pos + 1)); if ($k = = ' Set-cookie ') {//Update COO Kie if ($this->keepcontext) {$this->context->addcookie (new Sincookie ($v));} else {//Add head inside to $this->response->setheader ($k, $v);} else {//First row data//parse response state $preg = '/^ (s*) (s*) (. *) $/'; Preg_match_all ($preg, $h, $arr); Isset ($arr [1][0]) & $this-&G T;response->scheme = Trim ($arr [1][0]); Isset ($arr [2][0]) & $this->response->stasus = Trim ($arr [2][0]); Isset ($arr [3][0]) & $this->response->code = Trim ($arr [3][0]); }//Get response body length $len = (int) $this->response->header[' content-length ']; $res = '; The following loop reads the body while (!feof ($fp) && $len > 0) {$c = Fread ($fp, $len); $res. = $c; $len = strlen ($c);} $this-&G T;response->body = $res; }//OffClosed Socket fclose ($FP); Save return to context maintenance $this->context->refrer = $url; ////demo/Now let begin test it $client = new sinhttpclient (); Create a client $client->get (' http://www.baidu.com/'); Get Echo $client->response->body; Echo?>

I hope this article will help you with your PHP programming.

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.