4 Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
5 Manual: http://scripts.incutio.com/httpclient/
7 Copyright © 2003 Incutio Limited
8 License: http://www.opensource.org/licenses/artistic-license.php
10 File upload and xmlrpc support by Reini Urban for PhpWiki, 2006-12-28 18:12:47
21 public $postdata = '';
22 public $cookies = array();
24 public $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
25 public $accept_encoding = 'gzip';
26 public $accept_language = 'en-us';
27 public $user_agent = 'Incutio HttpClient v1.0';
28 public $boundary = "xYzZY"; // FIXME: check if this string doesn't occur in the data
31 public $use_gzip = true;
32 public $persist_cookies = true; // If true, received cookies are placed in the $this->cookies array ready for the next request
33 // Note: This currently ignores the cookie path (and time) completely. Time is not important,
34 // but path could possibly lead to security problems.
35 public $persist_referers = true; // For each request, sends path of last request as referer
36 public $debug = false;
37 public $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
38 public $max_redirects = 5;
39 public $headers_only = false; // If true, stops receiving once headers have been read.
40 // Basic authorization variables
45 public $headers = array();
49 public $redirect_count = 0;
50 public $cookie_host = '';
52 function HttpClient($host = 'localhost', $port = 80)
58 function get($path, $data = false)
61 $this->method = 'GET';
63 $this->path .= '?' . $this->buildQueryString($data);
65 return $this->doRequest();
68 function post($path, $data)
71 $this->method = 'POST';
72 $this->postdata = $this->buildQueryString($data);
73 return $this->doRequest();
76 function postfile($path, $filename)
79 $this->method = 'POST';
80 $boundary = $this->boundary; //"httpclient_boundary";
81 $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\"";
82 $basename = basename($filename);
85 . "Content-Disposition: form-data; filename=\"$basename\"\r\n"
86 . "Content-Type: application/octet-stream\r\n\r\n";
87 $this->postdata .= join("", file($filename));
88 $this->postdata .= "\r\n\r\n--$boundary--\r\n";
89 return $this->doRequest();
92 function buildQueryString($data)
95 if (is_array($data)) {
96 // Change data in to postable data
97 foreach ($data as $key => $val) {
99 foreach ($val as $val2) {
100 $querystring .= urlencode($key) . '=' . urlencode($val2) . '&';
103 $querystring .= urlencode($key) . '=' . urlencode($val) . '&';
106 $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
108 $querystring = $data;
115 // Performs the actual HTTP request, returning true or false depending on outcome
116 // Ensure that the PHP timeout is longer than the socket timeout
117 longer_timeout($this->timeout);
118 if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
122 $this->errormsg = 'Socket creation failed (-3)';
125 $this->errormsg = 'DNS lookup failure (-4)';
128 $this->errormsg = 'Connection refused or timed out (-5)';
131 $this->errormsg = 'Connection failed (' . $errno . ')';
132 $this->errormsg .= ' ' . $errstr;
133 $this->debug($this->errormsg);
137 socket_set_timeout($fp, $this->timeout);
138 if ($this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata))
139 $request = $this->buildRequest("text/xml"); //xmlrpc
140 else if ($this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
144 $boundary = $this->boundary;
145 $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
147 $request = $this->buildRequest();
148 $this->debug('Request', $request);
149 fwrite($fp, $request);
150 // Reset all the variables that should not persist between requests
151 $this->headers = array();
153 $this->errormsg = '';
154 // Set a couple of flags
157 // Now start reading back the response
159 $line = fgets($fp, 4096);
161 // Deal with first line of returned data
163 if ($line === false) {
164 $this->errormsg = "Empty " . $this->method . " response";
167 if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
168 $this->errormsg = "Status code line invalid: " . htmlentities($line);
169 $this->debug($this->errormsg);
172 // $http_version = $m[1]; // not used
173 $this->status = $m[2];
174 $status_string = $m[3];
175 $this->debug(trim($line));
179 if (trim($line) == '') {
181 $this->debug('Received Headers', $this->headers);
182 if ($this->headers_only) {
183 break; // Skip the rest of the input
187 if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
188 // Skip to the next header
191 $key = strtolower(trim($m[1]));
193 // Deal with the possibility of multiple headers of same name
194 if (isset($this->headers[$key])) {
195 if (is_array($this->headers[$key])) {
196 $this->headers[$key][] = $val;
198 $this->headers[$key] = array($this->headers[$key], $val);
201 $this->headers[$key] = $val;
205 // We're not in the headers, so append the line to the contents
206 $this->content .= $line;
209 // If data is compressed, uncompress it
210 if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
211 $this->debug('Content is gzip encoded, unzipping it');
212 $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
213 $this->content = gzinflate($this->content);
215 // If $persist_cookies, deal with any cookies
216 if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
217 $cookies = $this->headers['set-cookie'];
218 if (!is_array($cookies)) {
219 $cookies = array($cookies);
221 foreach ($cookies as $cookie) {
222 if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
223 $this->cookies[$m[1]] = $m[2];
226 // Record domain of cookies for security reasons
227 $this->cookie_host = $this->host;
229 if ($this->status == '401') {
230 $this->errormsg = '401 ' . $status_string;
233 // If $persist_referers, set the referer ready for the next request
234 if (isset($this->persist_referers)) {
235 $this->debug('Persisting referer: ' . $this->getRequestURL());
236 $this->referer = $this->getRequestURL();
238 // Finally, if handle_redirects and a redirect is sent, do that
239 if (isset($this->handle_redirects)) {
240 if (++$this->redirect_count >= $this->max_redirects) {
241 $this->errormsg = 'Number of redirects exceeded maximum (' . $this->max_redirects . ')';
242 $this->debug($this->errormsg);
243 $this->redirect_count = 0;
246 $location = isset($this->headers['location']) ? $this->headers['location'] : '';
247 $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
248 if ($location || $uri) {
249 $url = parse_url($location . $uri);
250 if ($this->method == 'POST')
251 return $this->doRequest();
253 // This will FAIL if redirect is to a different site
254 return $this->get($url['path']);
260 function buildRequest($ContentType = 'application/x-www-form-urlencoded')
263 // Using 1.1 leads to all manner of problems, such as "chunked" encoding
264 $headers[] = "{$this->method} {$this->path} HTTP/1.0";
265 $headers[] = "Host: {$this->host}";
266 $headers[] = "User-Agent: {$this->user_agent}";
267 $headers[] = "Accept: {$this->accept}";
268 if ($this->use_gzip) {
269 $headers[] = "Accept-encoding: {$this->accept_encoding}";
271 $headers[] = "Accept-language: {$this->accept_language}";
272 if (!empty($this->referer)) {
273 $headers[] = "Referer: {$this->referer}";
276 if (!empty($this->cookies)) {
277 $cookie = 'Cookie: ';
278 foreach ($this->cookies as $key => $value) {
279 $cookie .= "$key=$value; ";
281 $headers[] = $cookie;
283 // Basic authentication
284 if (!empty($this->username) && !empty($this->password)) {
285 $headers[] = 'Authorization: BASIC ' . base64_encode($this->username . ':' . $this->password);
287 // If this is a POST, set the content type and length
288 if ($this->postdata) {
289 $headers[] = 'Content-Type: ' . $ContentType;
290 $headers[] = 'Content-Length: ' . strlen($this->postdata);
292 $request = implode("\r\n", $headers) . "\r\n\r\n" . $this->postdata;
298 return $this->status;
301 function getContent()
303 return $this->content;
306 function getHeaders()
308 return $this->headers;
311 function getHeader($header)
313 $header = strtolower($header);
314 if (isset($this->headers[$header])) {
315 return $this->headers[$header];
323 return $this->errormsg;
326 function getCookies()
328 return $this->cookies;
331 function getRequestURL()
333 $url = 'http://' . $this->host;
334 if ($this->port != 80) {
335 $url = 'https://' . $this->host;
336 $url .= ':' . $this->port;
343 function setUserAgent($string)
345 $this->user_agent = $string;
348 function setAuthorization($username, $password)
350 $this->username = $username;
351 $this->password = $password;
354 function setCookies($array)
356 $this->cookies = $array;
359 // Option setting methods
360 function useGzip($boolean)
362 $this->use_gzip = $boolean;
365 function setPersistCookies($boolean)
367 $this->persist_cookies = $boolean;
370 function setPersistReferers($boolean)
372 $this->persist_referers = $boolean;
375 function setHandleRedirects($boolean)
377 $this->handle_redirects = $boolean;
380 function setMaxRedirects($num)
382 $this->max_redirects = $num;
385 function setHeadersOnly($boolean)
387 $this->headers_only = $boolean;
390 function setDebug($boolean)
392 $this->debug = $boolean;
395 // "Quick" static methods
396 static function quickGet($url)
398 $bits = parse_url($url);
399 $host = $bits['host'];
400 $port = isset($bits['port']) ? $bits['port'] : 80;
401 $path = isset($bits['path']) ? $bits['path'] : '/';
402 if (isset($bits['query'])) {
403 $path .= '?' . $bits['query'];
405 $client = new HttpClient($host, $port);
406 if (!$client->get($path)) {
409 return $client->getContent();
413 static function quickPost($url, $data)
415 $bits = parse_url($url);
416 $host = $bits['host'];
417 $port = isset($bits['port']) ? $bits['port'] : 80;
418 $path = isset($bits['path']) ? $bits['path'] : '/';
419 $client = new HttpClient($host, $port);
420 if (!$client->post($path, $data)) {
423 return $client->getContent();
427 function debug($msg, $object = null)
430 print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg;
434 $content = htmlentities(ob_get_contents());
436 print '<pre>' . $content . '</pre>';
447 // c-hanging-comment-ender-p: nil
448 // indent-tabs-mode: nil