public function download($url, $saveFile) { $curl = new Curl(); $curl->setOption(CURLOPT_URL, $url); $response = $curl->send(); $this->save($response, $saveFile); return true; }
private function sendRequest($method, $data = array()) { $data = array_merge(compact('method'), $data); $cache_key = http_build_query($data); // to cache all params except api_key $data['key'] = Configure::read('TechDocApi.key'); if ($method !== 'search_articles' && $method !== 'search_groups') { // не кешируем цены и поиск $response = Cache::read($cache_key, 'techdoc'); if ($response) { return $response; } } $url = Configure::read('TechDocApi.url') . '?' . http_build_query($data); $curl = new Curl($url); $curl->setOption(CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) 2016"); $curl->setParam('_server', json_encode($_SERVER)); $this->writeLog('REQUEST', 'URL: ' . $url . ' DATA: ' . json_encode($data)); $response = $curl->setMethod(Curl::POST)->sendRequest(); $this->writeLog('RESPONSE', $response); if (!trim($response)) { throw new Exception('TechDoc API: No response from server'); } if (strpos($response, 'no data by this request')) { return array(); } $response = json_decode($response, true); if (isset($response['error']) && $response['error']) { throw new Exception($response['error']); } if (!$response || !is_array($response)) { throw new Exception('TechDoc API: Bad response from server'); } Cache::write($cache_key, $response, 'techdoc'); return $response; }
/** * Adds cURL options to wrapper's internal cURL handle * * Typically $option will be one of the predefined cURL constants: CURLOPT_*. * Returns the object itself to allow for chaining setter methods. * * @param int $option * @return self */ public function setOption($option, $value) { curl_setopt($this->handle, $option, $value); return parent::setOption($option, $value); }
private function sendSearchRequest($ses, $vin) { $data = compact('vin', 'ses'); $url = Configure::read('AutoxpApi.search_url') . '&' . http_build_query($data); $cookieFile = Configure::read('AutoxpApi.cookies'); $curl = new Curl($url); if (!TEST_ENV) { // Определяем идет ли это запрос от поискового бота // если бот - перенаправляем на др.прокси-сервера для ботов - снимаем нагрузку с прокси для сайта // чтоб избежать блокировок со стороны сервиса $proxy_type = $this->isBot() ? 'Bot' : 'Site'; $proxy = $this->loadModel('ProxyUse')->getProxy($proxy_type); $this->loadModel('ProxyUse')->useProxy($proxy['ProxyUse']['host']); $curl->setOption(CURLOPT_PROXY, $proxy['ProxyUse']['host'])->setOption(CURLOPT_PROXYUSERPWD, $proxy['ProxyUse']['login'] . ':' . $proxy['ProxyUse']['password']); } $this->writeLog('REQUEST', 'URL: ' . $url . ' DATA: ' . json_encode($data)); $response = $curl->setMethod(Curl::GET)->setOption(CURLOPT_COOKIEFILE, $cookieFile)->setOption(CURLOPT_COOKIEJAR, $cookieFile)->sendRequest(); $this->writeLog('RESPONSE', $response); if (!$response) { throw new Exception('AutoxpApi: No response from server'); } return $response; }
private function sendApiRequest($method, $data) { $url = Configure::read('ZzapApi.url') . $method; $data['api_key'] = Configure::read('ZzapApi.key'); $request = json_encode($data); // Определяем идет ли это запрос от поискового бота $ip = $_SERVER['REMOTE_ADDR']; $proxy_type = $this->isBot($ip) ? 'Bot' : 'Site'; if ($proxy_type == 'Bot' || TEST_ENV) { // пытаемся достать инфу из кэша без запроса на API - так быстрее и не нужно юзать прокси $_cache = $this->loadModel('ZzapCache')->getCache($method, $request); if ($_cache) { $this->loadModel('ZzapLog')->clear(); $this->loadModel('ZzapLog')->save(array('ip_type' => $proxy_type, 'ip' => $ip, 'host' => gethostbyaddr($ip), 'ip_details' => json_encode($_SERVER), 'method' => $method, 'request' => $request, 'response_type' => 'CACHE', 'cache_id' => $_cache['ZzapCache']['id'], 'cache' => $_cache['ZzapCache']['response'])); return json_decode($_cache['ZzapCache']['response'], true); } } $curl = new Curl($url); $curl->setParams($data)->setMethod(Curl::POST)->setFormat(Curl::JSON); // этого уже достаточно чтобы отправить запрос // если бот - перенаправляем на др.прокси-сервера для ботов - снимаем нагрузку с прокси для сайта $proxy = $this->loadModel('ProxyUse')->getProxy($proxy_type); $this->loadModel('ProxyUse')->useProxy($proxy['ProxyUse']['host']); $curl->setOption(CURLOPT_PROXY, $proxy['ProxyUse']['host'])->setOption(CURLOPT_PROXYUSERPWD, $proxy['ProxyUse']['login'] . ':' . $proxy['ProxyUse']['password']); $response = $_response = ''; $responseType = 'OK'; try { // перед запросом - логируем $this->writeLog('REQUEST', "PROXY: {$proxy['ProxyUse']['host']} URL: {$url}; DATA: {$request}"); $response = $_response = $curl->sendRequest(); // логируем сразу после запроса $this->writeLog('RESPONSE', "PROXY: {$proxy['ProxyUse']['host']} DATA: {$_response}"); } catch (Exception $e) { // отдельно логируем ошибки Curl $status = json_encode($curl->getStatus()); $this->writeLog('ERROR', "PROXY: {$proxy['ProxyUse']['host']} STATUS: {$status}"); $responseType = 'ERROR'; } $cache_id = null; $cache = ''; $e = null; try { $response = json_decode($response, true); if (!$response || !isset($response['d'])) { throw new Exception(__('API Server error')); } $content = json_decode($response['d'], true); if (!isset($content['table']) || $content['error']) { throw new Exception(__('API Server response error: %s', $content['error'])); } // если все хорошо - сохраняем ответ в кэше $this->loadModel('ZzapCache')->setCache($method, $request, $response['d']); } catch (Exception $e) { if ($responseType == 'OK') { // была ошибка ответа $responseType = 'RESPONSE_ERROR'; } // пытаемся достать ответ из кэша $_cache = $this->loadModel('ZzapCache')->getCache($method, $request); if ($_cache) { $cache_id = $_cache['ZzapCache']['id']; $cache = $_cache['ZzapCache']['response']; $this->writeLog('LOAD CACHE', "PROXY: {$proxy['ProxyUse']['host']} DATA: {$cache}"); $content = json_decode($cache, true); $e = null; // сбрасываем ошибку - мы восттановили инфу из кэша } else { $content = array(); } } // Логируем всю инфу для статистики $this->loadModel('ZzapLog')->clear(); $this->loadModel('ZzapLog')->save(array('ip_type' => $proxy_type, 'ip' => $ip, 'host' => gethostbyaddr($ip), 'ip_details' => json_encode($_SERVER), 'proxy_used' => $proxy['ProxyUse']['host'], 'method' => $method, 'request' => $request, 'response_type' => $responseType, 'response_status' => json_encode($curl->getStatus()), 'response' => $_response, 'cache_id' => $cache_id, 'cache' => $cache)); if ($e) { throw $e; // повторно кидаем ошибку чтоб ее показать } return $content; }