您好,欢迎访问一九零五行业门户网

PHP的一个简单封装的HTTP类

cookies array ready for the next request // note: this currently ignores the cookie path (and time) completely. time is not important, // but path could possibly lead to security problems. var $persist_referers = true; // for each request, sends path of last request as referer var $debug = false; var $handle_redirects = true; // auaomtically redirect if location or uri header is found var $max_redirects = 5; var $headers_only = false; // if true, stops receiving once headers have been read. // basic authorization variables var $username; var $password; // response vars var $status; var $headers = array(); var $content = ''; var $errormsg; // tracker variables var $redirect_count = 0; var $cookie_host = ''; function httpclient($host, $port=80) { $this->host = $host; $this->port = $port; } /** * as the httpclient manual said: * executes a get request for the specified path. if $data is specified, appends it to a query string as part of the get request. * $data can be an array of key value pairs, in which case a matching query string will be constructed. returns true on success and false on failure. * if false, an error message describing the problem encountered can be accessed using the geterror() method. * for example: like http://ecc.tencent.com/index.php?c=job&m=req * * @param $path ecc.tencent.com * @param bool $data [c=>job,m=req] * @return bool */ function get($path, $data = false) { $this->path = $path; $this->method = 'get'; if ($data) { //$this->path .= '?'.$this->buildquerystring($data); $this->path .= $this->buildquerystring($data); } return $this->dorequest(); } /** * executes a post request to the specified path, sending the information from specified in $data. * $data can be an array of key value pairs, in which case a matching post request will be constructed. * returns true on success and false on failure. if false, an error message describing the problem encountered can be accessed using the geterror() method. * * @param $path * @param $data * @return bool */ function post($path, $data) { $this->path = $path; $this->method = 'post'; $this->postdata = $this->buildquerystring($data); return $this->dorequest(); } function buildquerystring($data) { $querystring = ''; if (is_array($data)) { // change data in to postable data foreach ($data as $key => $val) { if (is_array($val)) { foreach ($val as $val2) { $querystring .= urlencode($key).'='.urlencode($val2).'&'; } } else { $querystring .= urlencode($key).'='.urlencode($val).'&'; } } $querystring = substr($querystring, 0, -1); // eliminate unnecessary & } else { $querystring = $data; } return $querystring; } function dorequest() { // performs the actual http request, returning true or false depending on outcome if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { // set error message switch($errno) { case -3: $this->errormsg = 'socket creation failed (-3)'; case -4: $this->errormsg = 'dns lookup failure (-4)'; case -5: $this->errormsg = 'connection refused or timed out (-5)'; default: $this->errormsg = 'connection failed ('.$errno.')'; $this->errormsg .= ' '.$errstr; $this->debug($this->errormsg); } return false; } socket_set_timeout($fp, $this->timeout); $request = $this->buildrequest(); $this->debug('request', $request); fwrite($fp, $request); // reset all the variables that should not persist between requests $this->headers = array(); $this->content = ''; $this->errormsg = ''; // set a couple of flags $inheaders = true; $atstart = true; // now start reading back the response while (!feof($fp)) { $line = fgets($fp, 4096); if ($atstart) { // deal with first line of returned data $atstart = false; if (!preg_match('/http\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { $this->errormsg = status code line invalid: .htmlentities($line); $this->debug($this->errormsg); return false; } $http_version = $m[1]; // not used $this->status = $m[2]; $status_string = $m[3]; // not used $this->debug(trim($line)); continue; } if ($inheaders) { if (trim($line) == '') { $inheaders = false; $this->debug('received headers', $this->headers); if ($this->headers_only) { break; // skip the rest of the input } continue; } if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { // skip to the next header continue; } $key = strtolower(trim($m[1])); $val = trim($m[2]); // deal with the possibility of multiple headers of same name if (isset($this->headers[$key])) { if (is_array($this->headers[$key])) { $this->headers[$key][] = $val; } else { $this->headers[$key] = array($this->headers[$key], $val); } } else { $this->headers[$key] = $val; } continue; } // we're not in the headers, so append the line to the contents $this->content .= $line; } fclose($fp); // if data is compressed, uncompress it if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { $this->debug('content is gzip encoded, unzipping it'); $this->content = substr($this->content, 10); // see http://www.php.net/manual/en/function.gzencode.php $this->content = gzinflate($this->content); } // if $persist_cookies, deal with any cookies if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { $cookies = $this->headers['set-cookie']; if (!is_array($cookies)) { $cookies = array($cookies); } foreach ($cookies as $cookie) { if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { $this->cookies[$m[1]] = $m[2]; } } // record domain of cookies for security reasons $this->cookie_host = $this->host; } // if $persist_referers, set the referer ready for the next request if ($this->persist_referers) { $this->debug('persisting referer: '.$this->getrequesturl()); $this->referer = $this->getrequesturl(); } // finally, if handle_redirects and a redirect is sent, do that if ($this->handle_redirects) { if (++$this->redirect_count >= $this->max_redirects) { $this->errormsg = 'number of redirects exceeded maximum ('.$this->max_redirects.')'; $this->debug($this->errormsg); $this->redirect_count = 0; return false; } $location = isset($this->headers['location']) ? $this->headers['location'] : ''; $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; if ($location || $uri) { $url = parse_url($location.$uri); // this will fail if redirect is to a different site return $this->get($url['path']); } } return true; } //拼装header function buildrequest() { $headers = array(); $headers[] = {$this->method} {$this->path} http/1.0; // using 1.1 leads to all manner of problems, such as chunked encoding $headers[] = host: {$this->host}; $headers[] = user-agent: {$this->user_agent}; $headers[] = accept: {$this->accept}; if ($this->use_gzip) { $headers[] = accept-encoding: {$this->accept_encoding}; } $headers[] = accept-language: {$this->accept_language}; if ($this->referer) { $headers[] = referer: {$this->referer}; } // cookies if ($this->cookies) { $cookie = 'cookie: '; foreach ($this->cookies as $key => $value) { $cookie .= $key=$value; ; } $headers[] = $cookie; } // basic authentication if ($this->username && $this->password) { $headers[] = 'authorization: basic '.base64_encode($this->username.':'.$this->password); } // if this is a post, set the content type and length if ($this->postdata) { $headers[] = 'content-type: application/x-www-form-urlencoded'; $headers[] = 'content-length: '.strlen($this->postdata); } $request = implode(\r\n, $headers).\r\n\r\n.$this->postdata; return $request; } function getstatus() { return $this->status; } function getcontent() { return $this->content; } function getheaders() { return $this->headers; } function getheader($header) { $header = strtolower($header); if (isset($this->headers[$header])) { return $this->headers[$header]; } else { return false; } } function geterror() { return $this->errormsg; } function getcookies() { return $this->cookies; } function getrequesturl() { $url = 'http://'.$this->host; if ($this->port != 80) { $url .= ':'.$this->port; } $url .= $this->path; return $url; } // setter methods function setuseragent($string) { $this->user_agent = $string; } function setauthorization($username, $password) { $this->username = $username; $this->password = $password; } function setcookies($array) { $this->cookies = $array; } // option setting methods function usegzip($boolean) { $this->use_gzip = $boolean; } function setpersistcookies($boolean) { $this->persist_cookies = $boolean; } function setpersistreferers($boolean) { $this->persist_referers = $boolean; } function sethandleredirects($boolean) { $this->handle_redirects = $boolean; } function setmaxredirects($num) { $this->max_redirects = $num; } function setheadersonly($boolean) { $this->headers_only = $boolean; } function setdebug($boolean) { $this->debug = $boolean; } // quick static methods function quickget($url) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; if (isset($bits['query'])) { $path .= '?'.$bits['query']; } $client = new httpclient($host, $port); if (!$client->get($path)) { return false; } else { return $client->getcontent(); } } function quickpost($url, $data) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; $client = new httpclient($host, $port); if (!$client->post($path, $data)) { return false; } else { return $client->getcontent(); } } function debug($msg, $object = false) { if ($this->debug) { print 'httpclient debug: '.$msg; if ($object) { ob_start(); print_r($object); $content = htmlentities(ob_get_contents()); ob_end_clean(); print ''.$content.'
'; } print '
'; } }}?>
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了php的一个简单封装的http类,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息