diff options
-rw-r--r-- | url.class | 40 |
1 files changed, 31 insertions, 9 deletions
@@ -216,14 +216,22 @@ function is_reachable($timeout = 5) /** * Get simple URL with timeout. Can be called statically - * @url url to get, defaults to constructor URL - * @timeout timeout per read in milliseconds. + * @p parameter array with the following keys + * - url: url to get, defaults to constructor URL + * - timeout: timeout per read in milliseconds, defaults to 5000 + * - data: post data array with key-value pairs * @return contents of resulting page, considering redirects, excluding headers, or false on error */ -function get($url=null, $timeout=5000) +function get($p=null, $timeout=5000) { - if ($url) - $url = new it_url($url); + if (!is_array($p)) + $p = array('url' => $p); + + if (!isset($p['timeout'])) + $p['timeout'] = $timeout; + + if ($p['url']) + $url = new it_url($p['url']); else $url =& $this; # Must be reference for $url->result and $url->data to work @@ -233,10 +241,23 @@ function get($url=null, $timeout=5000) if ($url->protocol == 'http') { - if ($fp = @fsockopen($url->realhostname, $url->port, $errno, $errstr, $timeout/1000)) + if ($fp = @fsockopen($url->realhostname, $url->port, $errno, $errstr, $p['timeout']/1000)) { - stream_set_timeout($fp, intval($timeout/1000), ($timeout%1000)*1000); - @fputs($fp, "GET /$url->path HTTP/1.0\r\nHost: $url->realhostname\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; ITools)\r\n\r\n"); + # urlencode data pairs if is array + if (is_array($p['data'])) + { + $data_pairs = array(); + + foreach ($p['data'] as $key => $value) + $data_pairs[] = "$key=".urlencode($value); + + $p['data'] = implode('&', $data_pairs); + } + + $data = !empty($p['data']) ? "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($p['data']) . "\r\n\r\n" . $p['data'] : ""; + + stream_set_timeout($fp, intval($p['timeout']/1000), ($p['timeout']%1000)*1000); + @fputs($fp, (empty($data)?'GET':'POST') . " /$url->path HTTP/1.0\r\nHost: $url->realhostname\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; ITools)$data\r\n\r\n"); while (!feof($fp) && ($line = @fgets($fp, 10240)) && ($line = trim($line))) { @@ -244,8 +265,9 @@ function get($url=null, $timeout=5000) $url->headers[$parts[1]] = $url->result = $parts[2]; elseif (preg_match('#^Location: (https?://[^/]*)?(/)?(.*)$#', $line, $parts) && ($parts[1] != $url->url)) # Handle redirects (supports relative and global) { + unset($p['url']); $url->it_url($parts[1] ? $parts[1].$parts[2].$parts[3] : $url->protocol.'://'.$url->realhostname.($parts[2] ? $parts[2].$parts[3] : '/'.dirname($url->path).'/'.$parts[3])); - return $url->get(null, $timeout); + return $url->get($p); } elseif (preg_match('#^([^:]+): (.*)$#', $line, $parts)) $url->headers[$parts[1]] = $parts[2]; |