comparison Http.inc @ 93:8aadd7a23b68

Moved some functionality from common-functions into Http class. Reorganized Validator into a class hierarchy. Added functionality for validating with a buffer in addition to URLs.
author Tom Fredrik "BFG" Klaussen <bfg@blenning.no>
date Thu, 18 Oct 2012 16:44:48 +0200
parents
children 2370f4450983
comparison
equal deleted inserted replaced
92:f468365813c9 93:8aadd7a23b68
1 <?php
2 include_once 'ScriptIncludeCache.inc';
3
4 /// @cond
5 $baseDir = dirname(__FILE__);
6
7 $cache = ScriptIncludeCache::instance(__FILE__);
8 /// @endcond
9
10 class Http
11 {
12 static function headersToArray($response)
13 {
14 $headers = array();
15 $response = trim($response);
16 $str = explode("\n", $response);
17 $headers[''] = trim($str[0]);
18 foreach($str as $kv) {
19 $p = strpos($kv, ":");
20 if ($p) {
21 $key = substr($kv, 0, $p);
22 $value = trim(substr($kv, $p + 1));
23 $headers[$key] = $value;
24 }
25 }
26 return $headers;
27 }
28
29 /**
30 * Queries a URL for headers
31 *
32 * @param $url the url to query
33 * @return an associative array of all headers returned
34 */
35 static function getHeaders($url, $timeout = 1)
36 {
37 $response = @http_head($url, array("timeout" => $timeout), $info);
38
39 if (array_key_exists('error', $info) && $info['error']) {
40 throw new RequestException($info);
41 }
42
43 return self::headersToArray($response);
44 }
45
46 static function postHeaders($url, $params, $timeout = 1)
47 {
48 $crl = curl_init();
49
50 $descriptorspec = array(
51 0 => array("pipe", "r"),
52 1 => array("pipe", "w"),
53 //2 => array("file", "/tmp/error-output.txt", "a")
54 );
55
56 //We use tac, since it buffers, and we don't care about the output
57 //being reordered.
58 $process = proc_open('tac | tac', $descriptorspec, $pipes);
59
60 curl_setopt ($crl, CURLOPT_URL, $url);
61 curl_setopt ($crl, CURLOPT_WRITEHEADER, $pipes[0]);
62 curl_setopt ($crl, CURLOPT_NOBODY, true);
63 curl_setopt ($crl, CURLOPT_POST, true);
64 curl_setopt ($crl, CURLOPT_POSTFIELDS, $params);
65
66 curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
67 curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
68 $ret = curl_exec($crl);
69 curl_close($crl);
70
71 fclose($pipes[0]);
72 $buf = fread($pipes[1], 8192);
73
74 return self::headersToArray($buf);
75 }
76 }
77 ?>