protected function _resolveTitle(Url $url) { if (!$url->isHttp()) { return $url->toString(); } $http = new Http(5); $res = $http->get($url); if (!$res->isSuccess()) { return $url->toString(); } $url = $res->url(); if (!preg_match('/^text\\/html/i', $res->header('content-type'))) { return $url->toString(); } $doc = new DOMDocument(); libxml_use_internal_errors(true); $result = $doc->loadHTML($res->body()); libxml_use_internal_errors(false); if (!$result) { return $url->toString(); } $xpath = new DOMXPath($doc); $els = $xpath->query('//title'); if (!$els->length) { return $url->toString(); } return $els->item(0)->textContent; }
public function testHttp() { $url = new Url('http://host/'); $this->assertTrue($url->isHttp()); $url = new Url('https://host/'); $this->assertTrue($url->isHttps()); }
public function request($method, Url $url, $data = null) { if (!$url->isHttp()) { throw new \Exception("URL scheme is not HTTP or HTTPS"); } $ch = curl_init((string) $url); curl_setopt($ch, CURLOPT_HEADER, true); if (!ini_get('open_basedir')) { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (isset($this->_timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); } if (isset($this->_cookies)) { curl_setopt($ch, CURLOPT_COOKIE, $this->_cookies); } if ($method == self::METHOD_HEAD) { curl_setopt($ch, CURLOPT_NOBODY, true); } elseif ($method == self::METHOD_POST) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data instanceof \Coast\File ? '@' . (string) $data : $data); } $response = curl_exec($ch); $url = new Url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $head = substr($response, 0, $size); $body = $method != self::METHOD_HEAD ? substr($response, $size) : null; $headers = []; if ($head) { $parts = explode("\r\n\r\n", $head); $head = $parts[count($parts) - 2]; $head = explode("\r\n", $head); $headers = []; foreach ($head as $header) { $parts = explode(':', $header, 2); if (count($parts) != 2) { continue; } $name = trim($parts[0]); $value = trim($parts[1]); $headers[$name] = $value; } } if (isset($headers['cookie'])) { $this->_cookies = $headers['cookie']; } curl_close($ch); return new \Coast\Http\Response($url, $status, $headers, $body); }