5 Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
6 Manual: http://scripts.incutio.com/httpclient/
8 Copyright © 2003 Incutio Limited
9 License: http://www.opensource.org/licenses/artistic-license.php
11 File upload and xmlrpc support by Reini Urban for PhpWiki, 2006-12-28 18:12:47
22 var $cookies = array();
24 var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
25 var $accept_encoding = 'gzip';
26 var $accept_language = 'en-us';
27 var $user_agent = 'Incutio HttpClient v1.0';
28 var $boundary = "xYzZY"; // FIXME: check if this string doesn't occur in the data
32 var $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 var $persist_referers = true; // For each request, sends path of last request as referer
37 var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
38 var $max_redirects = 5;
39 var $headers_only = false; // If true, stops receiving once headers have been read.
40 // Basic authorization variables
45 var $headers = array();
49 var $redirect_count = 0;
50 var $cookie_host = '';
52 function HttpClient($host='localhost', $port=80) {
56 function get($path, $data = false) {
58 $this->method = 'GET';
60 $this->path .= '?'.$this->buildQueryString($data);
62 return $this->doRequest();
64 function post($path, $data) {
66 $this->method = 'POST';
67 $this->postdata = $this->buildQueryString($data);
68 return $this->doRequest();
70 function postfile($path, $filename) {
72 $this->method = 'POST';
73 $boundary = $this->boundary; //"httpclient_boundary";
74 $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\"";
75 $basename = basename($filename);
78 ."Content-Disposition: form-data; filename=\"$basename\"\r\n"
79 ."Content-Type: application/octet-stream\r\n\r\n";
80 $this->postdata .= join("",file($filename));
81 $this->postdata .= "\r\n\r\n--$boundary--\r\n";
82 return $this->doRequest();
84 function buildQueryString($data) {
86 if (is_array($data)) {
87 // Change data in to postable data
88 foreach ($data as $key => $val) {
90 foreach ($val as $val2) {
91 $querystring .= urlencode($key).'='.urlencode($val2).'&';
94 $querystring .= urlencode($key).'='.urlencode($val).'&';
97 $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
104 function doRequest() {
105 // Performs the actual HTTP request, returning true or false depending on outcome
106 // Ensure that the PHP timeout is longer than the socket timeout
107 longer_timeout($this->timeout);
108 if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
112 $this->errormsg = 'Socket creation failed (-3)';
114 $this->errormsg = 'DNS lookup failure (-4)';
116 $this->errormsg = 'Connection refused or timed out (-5)';
118 $this->errormsg = 'Connection failed ('.$errno.')';
119 $this->errormsg .= ' '.$errstr;
120 $this->debug($this->errormsg);
124 socket_set_timeout($fp, $this->timeout);
125 if ( $this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata))
126 $request = $this->buildRequest("text/xml"); //xmlrpc
127 else if ( $this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
131 $boundary = $this->boundary;
132 $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
134 $request = $this->buildRequest();
135 $this->debug('Request', $request);
136 fwrite($fp, $request);
137 // Reset all the variables that should not persist between requests
138 $this->headers = array();
140 $this->errormsg = '';
141 // Set a couple of flags
144 // Now start reading back the response
146 $line = fgets($fp, 4096);
148 // Deal with first line of returned data
150 if ($line === false) {
151 $this->errormsg = "Empty ". $this->method. " response";
154 if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
155 $this->errormsg = "Status code line invalid: ".htmlentities($line);
156 $this->debug($this->errormsg);
159 $http_version = $m[1]; // not used
160 $this->status = $m[2];
161 $status_string = $m[3]; // not used
162 $this->debug(trim($line));
166 if (trim($line) == '') {
168 $this->debug('Received Headers', $this->headers);
169 if ($this->headers_only) {
170 break; // Skip the rest of the input
174 if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
175 // Skip to the next header
178 $key = strtolower(trim($m[1]));
180 // Deal with the possibility of multiple headers of same name
181 if (isset($this->headers[$key])) {
182 if (is_array($this->headers[$key])) {
183 $this->headers[$key][] = $val;
185 $this->headers[$key] = array($this->headers[$key], $val);
188 $this->headers[$key] = $val;
192 // We're not in the headers, so append the line to the contents
193 $this->content .= $line;
196 // If data is compressed, uncompress it
197 if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
198 $this->debug('Content is gzip encoded, unzipping it');
199 $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
200 $this->content = gzinflate($this->content);
202 // If $persist_cookies, deal with any cookies
203 if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
204 $cookies = $this->headers['set-cookie'];
205 if (!is_array($cookies)) {
206 $cookies = array($cookies);
208 foreach ($cookies as $cookie) {
209 if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
210 $this->cookies[$m[1]] = $m[2];
213 // Record domain of cookies for security reasons
214 $this->cookie_host = $this->host;
216 if ($this->status == '401') {
217 $this->errormsg = '401 ' . $status_string;
220 // If $persist_referers, set the referer ready for the next request
221 if (isset($this->persist_referers)) {
222 $this->debug('Persisting referer: '.$this->getRequestURL());
223 $this->referer = $this->getRequestURL();
225 // Finally, if handle_redirects and a redirect is sent, do that
226 if (isset($this->handle_redirects)) {
227 if (++$this->redirect_count >= $this->max_redirects) {
228 $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
229 $this->debug($this->errormsg);
230 $this->redirect_count = 0;
233 $location = isset($this->headers['location']) ? $this->headers['location'] : '';
234 $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
235 if ($location || $uri) {
236 $url = parse_url($location.$uri);
237 if ($this->method == 'POST')
238 return $this->doRequest();
240 // This will FAIL if redirect is to a different site
241 return $this->get($url['path']);
247 function buildRequest($ContentType = 'application/x-www-form-urlencoded') {
249 // Using 1.1 leads to all manner of problems, such as "chunked" encoding
250 $headers[] = "{$this->method} {$this->path} HTTP/1.0";
251 $headers[] = "Host: {$this->host}";
252 $headers[] = "User-Agent: {$this->user_agent}";
253 $headers[] = "Accept: {$this->accept}";
254 if ($this->use_gzip) {
255 $headers[] = "Accept-encoding: {$this->accept_encoding}";
257 $headers[] = "Accept-language: {$this->accept_language}";
258 if (!empty($this->referer)) {
259 $headers[] = "Referer: {$this->referer}";
262 if (!empty($this->cookies)) {
263 $cookie = 'Cookie: ';
264 foreach ($this->cookies as $key => $value) {
265 $cookie .= "$key=$value; ";
267 $headers[] = $cookie;
269 // Basic authentication
270 if (!empty($this->username) && !empty($this->password)) {
271 $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
273 // If this is a POST, set the content type and length
274 if ($this->postdata) {
275 $headers[] = 'Content-Type: ' . $ContentType;
276 $headers[] = 'Content-Length: '.strlen($this->postdata);
278 $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
281 function getStatus() {
282 return $this->status;
284 function getContent() {
285 return $this->content;
287 function getHeaders() {
288 return $this->headers;
290 function getHeader($header) {
291 $header = strtolower($header);
292 if (isset($this->headers[$header])) {
293 return $this->headers[$header];
298 function getError() {
299 return $this->errormsg;
301 function getCookies() {
302 return $this->cookies;
304 function getRequestURL() {
305 $url = 'http://'.$this->host;
306 if ($this->port != 80) {
307 $url = 'https://'.$this->host;
308 $url .= ':'.$this->port;
314 function setUserAgent($string) {
315 $this->user_agent = $string;
317 function setAuthorization($username, $password) {
318 $this->username = $username;
319 $this->password = $password;
321 function setCookies($array) {
322 $this->cookies = $array;
324 // Option setting methods
325 function useGzip($boolean) {
326 $this->use_gzip = $boolean;
328 function setPersistCookies($boolean) {
329 $this->persist_cookies = $boolean;
331 function setPersistReferers($boolean) {
332 $this->persist_referers = $boolean;
334 function setHandleRedirects($boolean) {
335 $this->handle_redirects = $boolean;
337 function setMaxRedirects($num) {
338 $this->max_redirects = $num;
340 function setHeadersOnly($boolean) {
341 $this->headers_only = $boolean;
343 function setDebug($boolean) {
344 $this->debug = $boolean;
346 // "Quick" static methods
347 function quickGet($url) {
348 $bits = parse_url($url);
349 $host = $bits['host'];
350 $port = isset($bits['port']) ? $bits['port'] : 80;
351 $path = isset($bits['path']) ? $bits['path'] : '/';
352 if (isset($bits['query'])) {
353 $path .= '?'.$bits['query'];
355 $client = new HttpClient($host, $port);
356 if (!$client->get($path)) {
359 return $client->getContent();
362 function quickPost($url, $data) {
363 $bits = parse_url($url);
364 $host = $bits['host'];
365 $port = isset($bits['port']) ? $bits['port'] : 80;
366 $path = isset($bits['path']) ? $bits['path'] : '/';
367 $client = new HttpClient($host, $port);
368 if (!$client->post($path, $data)) {
371 return $client->getContent();
374 function debug($msg, $object = false) {
376 print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
380 $content = htmlentities(ob_get_contents());
382 print '<pre>'.$content.'</pre>';
393 // c-hanging-comment-ender-p: nil
394 // indent-tabs-mode: nil