HttpClient.class.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. class HttpClient {
  3. // Request vars
  4. var $host;
  5. var $port;
  6. var $path;
  7. var $method;
  8. var $postdata = '';
  9. var $cookies = array();
  10. var $referer;
  11. var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
  12. var $accept_encoding = 'gzip';
  13. var $accept_language = 'en-us';
  14. var $user_agent = 'Incutio HttpClient v0.9';
  15. var $timeout = 20;
  16. var $use_gzip = true;
  17. var $persist_cookies = true;
  18. var $persist_referers = true;
  19. var $debug = false;
  20. var $handle_redirects = true;
  21. var $max_redirects = 5;
  22. var $headers_only = false;
  23. var $username;
  24. var $password;
  25. var $status;
  26. var $headers = array();
  27. var $content = '';
  28. var $errormsg;
  29. var $redirect_count = 0;
  30. var $cookie_host = '';
  31. function __construct($host, $port=80) {
  32. $this->host = $host;
  33. $this->port = $port;
  34. }
  35. function get($path, $data = false) {
  36. $this->path = $path;
  37. $this->method = 'GET';
  38. if ($data) {
  39. $this->path .= '?'.$this->buildQueryString($data);
  40. }
  41. return $this->doRequest();
  42. }
  43. function post($path, $data) {
  44. $this->path = $path;
  45. $this->method = 'POST';
  46. $this->postdata = $this->buildQueryString($data);
  47. return $this->doRequest();
  48. }
  49. function buildQueryString($data) {
  50. $querystring = '';
  51. if (is_array($data)) {
  52. foreach ($data as $key => $val) {
  53. if (is_array($val)) {
  54. foreach ($val as $val2) {
  55. $querystring .= urlencode($key).'='.urlencode($val2).'&';
  56. }
  57. } else {
  58. $querystring .= urlencode($key).'='.urlencode($val).'&';
  59. }
  60. }
  61. $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
  62. } else {
  63. $querystring = $data;
  64. }
  65. return $querystring;
  66. }
  67. function doRequest() {
  68. if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
  69. switch($errno) {
  70. case -3:
  71. $this->errormsg = 'Socket creation failed (-3)';
  72. case -4:
  73. $this->errormsg = 'DNS lookup failure (-4)';
  74. case -5:
  75. $this->errormsg = 'Connection refused or timed out (-5)';
  76. default:
  77. $this->errormsg = 'Connection failed ('.$errno.')';
  78. $this->errormsg .= ' '.$errstr;
  79. $this->debug($this->errormsg);
  80. }
  81. return false;
  82. }
  83. socket_set_timeout($fp, $this->timeout);
  84. $request = $this->buildRequest();
  85. $this->debug('Request', $request);
  86. fwrite($fp, $request);
  87. $this->headers = array();
  88. $this->content = '';
  89. $this->errormsg = '';
  90. $inHeaders = true;
  91. $atStart = true;
  92. while (!feof($fp)) {
  93. $line = fgets($fp, 4096);
  94. if ($atStart) {
  95. $atStart = false;
  96. if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
  97. $this->errormsg = "Status code line invalid: ".htmlentities($line);
  98. $this->debug($this->errormsg);
  99. return false;
  100. }
  101. $http_version = $m[1];
  102. $this->status = $m[2];
  103. $status_string = $m[3];
  104. $this->debug(trim($line));
  105. continue;
  106. }
  107. if ($inHeaders) {
  108. if (trim($line) == '') {
  109. $inHeaders = false;
  110. $this->debug('Received Headers', $this->headers);
  111. if ($this->headers_only) {
  112. break;
  113. }
  114. continue;
  115. }
  116. if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
  117. continue;
  118. }
  119. $key = strtolower(trim($m[1]));
  120. $val = trim($m[2]);
  121. if (isset($this->headers[$key])) {
  122. if (is_array($this->headers[$key])) {
  123. $this->headers[$key][] = $val;
  124. } else {
  125. $this->headers[$key] = array($this->headers[$key], $val);
  126. }
  127. } else {
  128. $this->headers[$key] = $val;
  129. }
  130. continue;
  131. }
  132. $this->content .= $line;
  133. }
  134. fclose($fp);
  135. if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
  136. $this->debug('Content is gzip encoded, unzipping it');
  137. $this->content = substr($this->content, 10);
  138. $this->content = gzinflate($this->content);
  139. }
  140. if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
  141. $cookies = $this->headers['set-cookie'];
  142. if (!is_array($cookies)) {
  143. $cookies = array($cookies);
  144. }
  145. foreach ($cookies as $cookie) {
  146. if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
  147. $this->cookies[$m[1]] = $m[2];
  148. }
  149. }
  150. $this->cookie_host = $this->host;
  151. }
  152. if ($this->persist_referers) {
  153. $this->debug('Persisting referer: '.$this->getRequestURL());
  154. $this->referer = $this->getRequestURL();
  155. }
  156. if ($this->handle_redirects) {
  157. if (++$this->redirect_count >= $this->max_redirects) {
  158. $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
  159. $this->debug($this->errormsg);
  160. $this->redirect_count = 0;
  161. return false;
  162. }
  163. $location = isset($this->headers['location']) ? $this->headers['location'] : '';
  164. $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
  165. if ($location || $uri) {
  166. $url = parse_url($location.$uri);
  167. return $this->get($url['path']);
  168. }
  169. }
  170. return true;
  171. }
  172. function buildRequest() {
  173. $headers = array();
  174. $headers[] = "{$this->method} {$this->path} HTTP/1.0";
  175. $headers[] = "Host: {$this->host}";
  176. $headers[] = "User-Agent: {$this->user_agent}";
  177. $headers[] = "Accept: {$this->accept}";
  178. if ($this->use_gzip) {
  179. $headers[] = "Accept-encoding: {$this->accept_encoding}";
  180. }
  181. $headers[] = "Accept-language: {$this->accept_language}";
  182. if ($this->referer) {
  183. $headers[] = "Referer: {$this->referer}";
  184. }
  185. if ($this->cookies) {
  186. $cookie = 'Cookie: ';
  187. foreach ($this->cookies as $key => $value) {
  188. $cookie .= "$key=$value; ";
  189. }
  190. $headers[] = $cookie;
  191. }
  192. if ($this->username && $this->password) {
  193. $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
  194. }
  195. if ($this->postdata) {
  196. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  197. $headers[] = 'Content-Length: '.strlen($this->postdata);
  198. }
  199. $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
  200. return $request;
  201. }
  202. function getStatus() {
  203. return $this->status;
  204. }
  205. function getContent() {
  206. return $this->content;
  207. }
  208. function getHeaders() {
  209. return $this->headers;
  210. }
  211. function getHeader($header) {
  212. $header = strtolower($header);
  213. if (isset($this->headers[$header])) {
  214. return $this->headers[$header];
  215. } else {
  216. return false;
  217. }
  218. }
  219. function getError() {
  220. return $this->errormsg;
  221. }
  222. function getCookies() {
  223. return $this->cookies;
  224. }
  225. function getRequestURL() {
  226. $url = 'http://'.$this->host;
  227. if ($this->port != 80) {
  228. $url .= ':'.$this->port;
  229. }
  230. $url .= $this->path;
  231. return $url;
  232. }
  233. function setUserAgent($string) {
  234. $this->user_agent = $string;
  235. }
  236. function setAuthorization($username, $password) {
  237. $this->username = $username;
  238. $this->password = $password;
  239. }
  240. function setCookies($array) {
  241. $this->cookies = $array;
  242. }
  243. function useGzip($boolean) {
  244. $this->use_gzip = $boolean;
  245. }
  246. function setPersistCookies($boolean) {
  247. $this->persist_cookies = $boolean;
  248. }
  249. function setPersistReferers($boolean) {
  250. $this->persist_referers = $boolean;
  251. }
  252. function setHandleRedirects($boolean) {
  253. $this->handle_redirects = $boolean;
  254. }
  255. function setMaxRedirects($num) {
  256. $this->max_redirects = $num;
  257. }
  258. function setHeadersOnly($boolean) {
  259. $this->headers_only = $boolean;
  260. }
  261. function setDebug($boolean) {
  262. $this->debug = $boolean;
  263. }
  264. function quickGet($url) {
  265. $bits = parse_url($url);
  266. $host = $bits['host'];
  267. $port = isset($bits['port']) ? $bits['port'] : 80;
  268. $path = isset($bits['path']) ? $bits['path'] : '/';
  269. if (isset($bits['query'])) {
  270. $path .= '?'.$bits['query'];
  271. }
  272. $client = new HttpClient($host, $port);
  273. if (!$client->get($path)) {
  274. return false;
  275. } else {
  276. return $client->getContent();
  277. }
  278. }
  279. function quickPost($url, $data) {
  280. $bits = parse_url($url);
  281. $host = $bits['host'];
  282. $port = isset($bits['port']) ? $bits['port'] : 80;
  283. $path = isset($bits['path']) ? $bits['path'] : '/';
  284. $client = new HttpClient($host, $port);
  285. if (!$client->post($path, $data)) {
  286. return false;
  287. } else {
  288. return $client->getContent();
  289. }
  290. }
  291. function debug($msg, $object = false) {
  292. if ($this->debug) {
  293. print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
  294. if ($object) {
  295. ob_start();
  296. print_r($object);
  297. $content = htmlentities(ob_get_contents());
  298. ob_end_clean();
  299. print '<pre>'.$content.'</pre>';
  300. }
  301. print '</div>';
  302. }
  303. }
  304. }
  305. ?>