Вход Регистрация
Файл: 233/CurlClass.php
Строк: 64
<?php
class CurlClassConfig
{
public 
$userAgent; #Юзер-агент
public $referer; #Реферер
public $proxytype; #Тип
public $proxy = FALSE; #Адрес прокси
public $cookiesFile = FALSE; #Путь к файлу с cookies
public $followLocations = TRUE; #Следовать ли редиректам?
public $timeout = 10; #Таймаут соединения
}

class 
CurlClass
{
private 
$_ch; #Дескриптор соединения
#####
#Инициализируем сеанс CURL
#
public function __construct ()
{
if (!
$this->_ch = curl_init ())
throw new 
Exception ('Неудалось установить сеанс CURL');
}
#
public function __destruct ()
{
curl_close ($this->_ch);
}
#
#Закрываем сеанс
#####

/**
* Выполнение запроса
* @param $config BugagaCurlClassConfig Объект с настройками запроса
*/
protected function execute (CurlClassConfig $config)
{
// Скачанные данные не выводить в поток (указывает, что функция curl_exec должна вернуть полученный ответ, а не отправить его сразу браузеру)
curl_setopt ($this->_ch, CURLOPT_RETURNTRANSFER, TRUE);

// Назначаем ЮЗЕР-АГЕНТ
curl_setopt ($this->_ch, CURLOPT_USERAGENT, $config->userAgent);

// Назначаем РЕФЕРЕР
curl_setopt ($this->_ch, CURLOPT_REFERER, $config->referer);

// Следовать ли редиректам?
curl_setopt ($this->_ch, CURLOPT_FOLLOWLOCATION, $config->followLocations);

// Таймаут
curl_setopt ($this->_ch, CURLOPT_TIMEOUT, $config->timeout);
curl_setopt ($this->_ch, CURLOPT_CONNECTTIMEOUT, $config->timeout);

// ТИП
curl_setopt ($this->_ch, CURLOPT_PROXYTYPE, $config->proxytype);
// Назначаем прокси-сервер
if ($config->proxy)
curl_setopt ($this->_ch, CURLOPT_PROXY, $config->proxy);



// Из-за особенностей curl КУКИ НАДО ИСПОЛЬЗОВАТЬ ПЕРЕД КАЖДЫМ CURL-ЗАПРОСОМ
// Используем куки
if ($config->cookiesFile)
{
// Задаем ПРАВИЛЬНЫЙ путь к файлу с куками
$ololo = dirname (__FILE__) . DIRECTORY_SEPARATOR . $config->cookiesFile;

curl_setopt ($this->_ch, CURLOPT_COOKIEJAR, $ololo);
curl_setopt ($this->_ch, CURLOPT_COOKIEFILE, $ololo);
}



        
$data = curl_exec ($this->_ch);

        if (
curl_errno ($this->_ch) == 5)
        {
            
curl_close ($this->_ch);
            throw new 
Exception ('Нерабочая прокся :-(');
        }

        return 
$data;
    }

    
/**
     * Загрузить страницу
     * 
     * @param $config BugagaCurlClassConfig Объект с настройками запроса
     * @param $url string Url получаемой страницы
     * @return string Исходный код страницы
     */
    
public function getPage (CurlClassConfig $config, $url)
    {
        
// Пишем url страницы
        
curl_setopt ($this->_ch, CURLOPT_URL, $url);

        
// Выполняем запрос
        
return $this->execute ($config);
    }

    
/**
     * Послать Post запрос. Внимание, передаваемые параметры никак экранировать не надо, они и так экранируются
     * 
     * @param $config BugagaCurlClassConfig Объект с настройками запроса
     * @param $url string Url страницы, на которую надо отправить запрос (другими словами, Action формы)
     * @param $params array Ассоциативный массив с параметрами
     * @return string Возвращенная страница
     */
    
public function sendPost (CurlClassConfig $config, $url, $params)
    {
        
/**
         * Отправляем POST запрос
         */
        // Пишем url страницы
        
curl_setopt ($this->_ch, CURLOPT_URL, $url);

        
curl_setopt ($this->_ch, CURLOPT_POST, TRUE);
        
// Назначаем значения передаваемых переменных
        
curl_setopt ($this->_ch, CURLOPT_POSTFIELDS, http_build_query ($params));

        
// Выполняем запрос
        
return $this->execute ($config);
    }

    
/**
     * Послать Get запрос
     */
    
public function sendGet (CurlClassConfig $config, $url, $params)
    {
        
    }

}
Онлайн: 4
Реклама