phplibrary/src/Connection/HttpRequest.php
2017-06-06 10:16:44 +03:00

111 lines
2.9 KiB
PHP

<?php
class Connection_HttpRequest
{
const POST = "POST";
const GET = "GET";
private $param = array(); // Параметры запроса
public $data = null; // Содержание
public $url; // Адресс
public $method; // Метод
public $port = 80;
public $host = "";
public $proxy_host = null;
public $proxy_port = null;
public $http_version = 'HTTP/1.1';
function __construct() {
$this->method = self::GET;
}
/**
* Возвращает заголовок соединения
*/
public function getHeader()
{
$result = $this->method . " " . $this->url . " " . $this->http_version . "\r\n";
$result .= "Host: ". $this->host ."\r\n";
foreach ($this->param as $key => $value) {
$result .= $key . ": " . $value . "\r\n";
}
$result .= "Connection: Close\r\n\r\n";
$result .= $this->data;
return $result;
}
/**
* Установка параметров запроса
* @parma string $name
* @parma string $value
*/
public function setParameter($name, $value)
{
$this->param[$name] = $value;
}
/**
* Метод запроса GET или POST
*/
public function setMethod($method)
{
$this->method = $method;
}
public function setUrl($url)
{
$this->url = $url;
$this->host = parse_url($this->url, PHP_URL_HOST);
}
public function getUrl()
{
return $this->url;
}
/**
* Содержание запроса
*/
public function setContent($data)
{
$this->setParameter ("Content-length", strlen($data));
$this->data = $data;
}
/**
* Посылает запрос и возвращает страницу
*/
public function getPage()
{
$host = ($this->proxy_host) ? $this->proxy_host : $this->host;
$port = ($this->proxy_port) ? $this->proxy_port : $this->port;
$errno = 0;
$errstr = '';
$socket = @fsockopen($host, $port, $errno, $errstr, 30);
if (is_resource($socket)) {
$header = $this->getHeader();
fwrite($socket, $header);
$result = null;
while (! feof($socket)) {
$result .= fgets($socket, 128);
}
fclose($socket);
return $result;
}
return null;
}
static function getJSON($url, $data) {
$c = new Connection_HttpRequest();
$c->http_version = "HTTP/1.0";
$query = http_build_query($data);
$c->setUrl($q = $url . '?' . $query);
$page = $c->getPage();
$response = new Connection_HttpResponse($page);
return json_decode((string) preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $response->getData()), true);
}
}