Mercurial > SimpleWebPresenter
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Http.inc Thu Oct 18 16:44:48 2012 +0200 @@ -0,0 +1,77 @@ +<?php +include_once 'ScriptIncludeCache.inc'; + +/// @cond +$baseDir = dirname(__FILE__); + +$cache = ScriptIncludeCache::instance(__FILE__); +/// @endcond + +class Http +{ + static function headersToArray($response) + { + $headers = array(); + $response = trim($response); + $str = explode("\n", $response); + $headers[''] = trim($str[0]); + foreach($str as $kv) { + $p = strpos($kv, ":"); + if ($p) { + $key = substr($kv, 0, $p); + $value = trim(substr($kv, $p + 1)); + $headers[$key] = $value; + } + } + return $headers; + } + + /** + * Queries a URL for headers + * + * @param $url the url to query + * @return an associative array of all headers returned + */ + static function getHeaders($url, $timeout = 1) + { + $response = @http_head($url, array("timeout" => $timeout), $info); + + if (array_key_exists('error', $info) && $info['error']) { + throw new RequestException($info); + } + + return self::headersToArray($response); + } + + static function postHeaders($url, $params, $timeout = 1) + { + $crl = curl_init(); + + $descriptorspec = array( + 0 => array("pipe", "r"), + 1 => array("pipe", "w"), + //2 => array("file", "/tmp/error-output.txt", "a") + ); + + //We use tac, since it buffers, and we don't care about the output + //being reordered. + $process = proc_open('tac | tac', $descriptorspec, $pipes); + + curl_setopt ($crl, CURLOPT_URL, $url); + curl_setopt ($crl, CURLOPT_WRITEHEADER, $pipes[0]); + curl_setopt ($crl, CURLOPT_NOBODY, true); + curl_setopt ($crl, CURLOPT_POST, true); + curl_setopt ($crl, CURLOPT_POSTFIELDS, $params); + + curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); + $ret = curl_exec($crl); + curl_close($crl); + + fclose($pipes[0]); + $buf = fread($pipes[1], 8192); + + return self::headersToArray($buf); + } +} +?> \ No newline at end of file
