<?php
/**
* Curl-обертка
**/
class Curl
{
protected static $curl;
private $ch;
private $user_agent;
private $http_header = [];
private $proxy = null;
private $proxy_type = null;
private $cookie_file = '/tmp/scr/cookie.txt';
private function __construct()
{
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION , true);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(self::$ch, CURLOPT_PROXY, $this->proxy);
if ($this->proxy_type == 'socks') {
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
}
curl_setopt($this->ch, CURLOPT_TIMEOUT, 60);
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 30);
}
public function __destruct()
{
if (isset($this->ch)) {
curl_close($this->ch);
}
}
public static function init()
{
return (is_null(self::$curl)) ?
self::$curl = new self :
self::$curl;
}
/**
* Установка user-agent
**/
public function setUserAgent($user_agent)
{
$this->user_agent = $user_agent;
}
/**
* Установка заголовка
**/
public function setHttpHeader($header, $ajax = false)
{
foreach ($header as $name => $value) {
$this->http_header[$name] = $name . ': ' . $value;
}
if ($ajax) {
$this->http_header += ["X-Requested-With" => "X-Requested-With: XMLHttpRequest"];
}
}
/**
* Установка cookie файла
**/
public function setCookieFile($dir)
{
$this->cookie_file = $dir;
}
/**
* Отправка запроса
**/
public function request($url, $post_data = null)
{
curl_setopt($this->ch, CURLOPT_URL, $url);
if (isset($post_data)) {
$post_data_encode = http_build_query($post_data);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data_encode);
}
return $this->exec();
}
public function exec()
{
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent);
if (isset($this->http_header)) {
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->http_header);
}
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie_file);
$response = curl_exec($this->ch);
return $response;
}
public function clear()
{
$this->user_agent = null;
$this->http_header = null;
$this->cookie_file = null;
self::$curl = null;
}
}