private function curlConnection($method = 'GET', $url, array $data = null, $timeout, $charset) { if (strtoupper($method) === 'POST') { $postFields = $data ? http_build_query($data, '', '&') : ""; $contentLength = "Content-length: " . strlen($postFields); $methodOptions = array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postFields); } else { $contentLength = null; $methodOptions = array(CURLOPT_HTTPGET => true); } $options = array(CURLOPT_HTTPHEADER => array("Content-Type: application/x-www-form-urlencoded; charset=" . $charset, $contentLength), CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_CONNECTTIMEOUT => $timeout); $options = $options + $methodOptions; $curl = curl_init(); curl_setopt_array($curl, $options); $resp = curl_exec($curl); $info = curl_getinfo($curl); $error = curl_errno($curl); $errorMessage = curl_error($curl); curl_close($curl); $this->setStatus((int) $info['http_code']); $this->setResponse((string) $resp); if ($error) { throw new Exception("CURL can't connect: {$errorMessage}"); return false; } else { return true; } }
/** * Sender constructor. * @param $url */ public function __construct($url) { $this->curlHandler = curl_init(); curl_setopt_array($this->curlHandler, $this->curlOptions); curl_setopt($this->curlHandler, CURLOPT_URL, $url); return $this; }
public function getDom($url, $post = false) { $f = fopen(CURL_LOG_FILE, 'a+'); // curl session log file if ($this->lastUrl) { $header[] = "Referer: {$this->lastUrl}"; } $curlOptions = array(CURLOPT_ENCODING => 'gzip,deflate', CURLOPT_AUTOREFERER => 1, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_URL => $url, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 9, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 0, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36", CURLOPT_COOKIEFILE => COOKIE_FILE, CURLOPT_COOKIEJAR => COOKIE_FILE, CURLOPT_STDERR => $f, CURLOPT_VERBOSE => true); if ($post) { // add post options $curlOptions[CURLOPT_POSTFIELDS] = $post; $curlOptions[CURLOPT_POST] = true; } $curl = curl_init(); curl_setopt_array($curl, $curlOptions); $data = curl_exec($curl); $this->lastUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); // get url we've been redirected to curl_close($curl); if ($this->dom) { $this->dom->clear(); $this->dom = false; } $dom = $this->dom = str_get_html($data); fwrite($f, "{$post}\n\n"); fwrite($f, "-----------------------------------------------------------\n\n"); fclose($f); return $dom; }
public function call($data) { if ($this->config->get('pp_express_test') == 1) { $api_endpoint = 'https://api-3t.sandbox.paypal.com/nvp'; $user = $this->config->get('pp_express_sandbox_username'); $password = $this->config->get('pp_express_sandbox_password'); $signature = $this->config->get('pp_express_sandbox_signature'); } else { $api_endpoint = 'https://api-3t.paypal.com/nvp'; $user = $this->config->get('pp_express_username'); $password = $this->config->get('pp_express_password'); $signature = $this->config->get('pp_express_signature'); } $settings = array('USER' => $user, 'PWD' => $password, 'SIGNATURE' => $signature, 'VERSION' => '109.0', 'BUTTONSOURCE' => 'Code4Fun_2.0_EC'); $this->log($data, 'Call data'); $defaults = array(CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_URL => $api_endpoint, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1", CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_POSTFIELDS => http_build_query(array_merge($data, $settings), '', "&")); $ch = curl_init(); curl_setopt_array($ch, $defaults); if (!($result = curl_exec($ch))) { $this->log(array('error' => curl_error($ch), 'errno' => curl_errno($ch)), 'cURL failed'); } $this->log($result, 'Result'); curl_close($ch); return $this->cleanReturn($result); }
/** * Makes an API request to elucidat * @param $headers * @param $fields * @param $url * @param $consumer_secret * @return mixed */ function call_elucidat($headers, $fields, $method, $url, $consumer_secret) { //Build a signature $headers['oauth_signature'] = build_signature($consumer_secret, array_merge($headers, $fields), $method, $url); //Build OAuth headers $auth_headers = 'Authorization:'; $auth_headers .= build_base_string($headers, ','); //Build the request string $fields_string = build_base_string($fields, '&'); //Set the headers $header = array($auth_headers, 'Expect:'); // Create curl options if (strcasecmp($method, "GET") == 0) { $url .= '?' . $fields_string; $options = array(CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false); } else { $options = array(CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_POST => count($fields), CURLOPT_POSTFIELDS => $fields_string); } //Init the request and set its params $request = curl_init(); curl_setopt_array($request, $options); //Make the request $response = curl_exec($request); $status = curl_getinfo($request, CURLINFO_HTTP_CODE); curl_close($request); return array('status' => $status, 'response' => json_decode($response, true)); }
function curl_setopt_array($handle, array $options) { if (array_values($options) != [null, null, null, null]) { $_SERVER['last_curl'] = $options; } \curl_setopt_array($handle, $options); }
/** * Returns the output of a remote URL. Any [curl option](http://php.net/curl_setopt) * may be used. * * // Do a simple GET request * $data = Remote::get($url); * * // Do a POST request * $data = Remote::get($url, array( * CURLOPT_POST => true, * CURLOPT_POSTFIELDS => http_build_query($array), * )); * * @param string remote URL * @param array curl options * @return string * @throws Exception */ public static function remote($url, array $options = null) { // The transfer must always be returned $options[CURLOPT_RETURNTRANSFER] = true; // Open a new remote connection $remote = curl_init($url); // Set connection options if (!curl_setopt_array($remote, $options)) { throw new Exception('Failed to set CURL options, check CURL documentation: http://php.net/curl_setopt_array'); } // Get the response $response = curl_exec($remote); // Get the response information $code = curl_getinfo($remote, CURLINFO_HTTP_CODE); if ($code and ($code < 200 or $code > 299)) { $error = $response; } elseif ($response === false) { $error = curl_error($remote); } // Close the connection curl_close($remote); if (isset($error)) { throw new Exception(sprintf('Error fetching remote %s [ status %s ] %s', $url, $code, $error)); } return $response; }
public static function setup($client_id, $client_secret, $podio_username, $podio_password, $options = array('session_manager' => null, 'curl_options' => array())) { // Setup client info self::$client_id = $client_id; self::$client_secret = $client_secret; // Setup curl self::$url = empty($options['api_url']) ? 'https://api.podio.com:443' : $options['api_url']; self::$debug = self::$debug ? self::$debug : false; self::$ch = curl_init(); self::$headers = array('Accept' => 'application/json'); curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, true); curl_setopt(self::$ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt(self::$ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt(self::$ch, CURLOPT_USERAGENT, 'Podio PHP Client/' . self::VERSION); curl_setopt(self::$ch, CURLOPT_HEADER, true); curl_setopt(self::$ch, CURLINFO_HEADER_OUT, true); if ($options && !empty($options['curl_options'])) { curl_setopt_array(self::$ch, $options['curl_options']); } if (!Cache::has('podio_oauth')) { self::authenticate_with_password($podio_username, $podio_password); Cache::put('podio_oauth', Podio::$oauth, 480); self::$oauth = Cache::get('podio_oauth'); } // Register shutdown function for debugging and session management register_shutdown_function('Podio::shutdown'); }
private function call() { $curl = array(CURLOPT_POST => 0, CURLOPT_HEADER => 0, CURLOPT_URL => 'http://www.marketinsg.com/index.php?route=information/news/system&url=' . rawurlencode(HTTP_CATALOG), CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1', CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0); $ch = curl_init(); curl_setopt_array($ch, $curl); if (!($result = curl_exec($ch))) { curl_close($ch); exit; } curl_close($ch); $encoding = mb_detect_encoding($result); if ($encoding == 'UTF-8') { $result = preg_replace('/[^(\\x20-\\x7F)]*/', '', $result); } $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "marketinsg_news WHERE text ='" . $this->db->escape($result) . "'"); if (!$query->num_rows) { $this->db->query("DELETE FROM " . DB_PREFIX . "marketinsg_news"); $this->db->query("INSERT INTO " . DB_PREFIX . "marketinsg_news SET text ='" . $this->db->escape($result) . "', date_added = NOW()"); } $disabled = '[{"title":"<strong>You have been disabled from MarketInSG.com news system<\\/strong>"}]'; if (addslashes($result) == addslashes($disabled)) { $this->db->query("INSERT INTO " . DB_PREFIX . "marketinsg_news_log SET date_checked = NOW(), status = 0"); } else { $this->db->query("INSERT INTO " . DB_PREFIX . "marketinsg_news_log SET date_checked = NOW(), status = 1"); } }
/** * {@inheritDoc} */ public function getContent($url) { if (!function_exists('curl_init')) { throw new ExtensionNotLoadedException('cURL has to be enabled.'); } $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_URL, $url); if ($this->timeout) { curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout); } if ($this->connectTimeout) { curl_setopt($c, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); } if ($this->userAgent) { curl_setopt($c, CURLOPT_USERAGENT, $this->userAgent); } if ($this->options && is_array($this->options) && count($this->options) > 0) { curl_setopt_array($c, $this->options); } $content = curl_exec($c); curl_close($c); if (false === $content) { $content = null; } return $content; }
/** * {@inheritdoc} */ public function requestApi($apiUrl, $params = array(), $method = 'POST') { $curlOpts = array(CURLOPT_URL => $apiUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_USERAGENT => 'payrexx-php/1.0.0', CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CAINFO => dirname(__DIR__) . '/certs/ca.pem'); $paramString = http_build_query($params, null, '&', PHP_QUERY_RFC3986); if ($method == 'GET') { if (!empty($params)) { $curlOpts[CURLOPT_URL] .= strpos($curlOpts[CURLOPT_URL], '?') === false ? '?' : '&'; $curlOpts[CURLOPT_URL] .= $paramString; } } else { $curlOpts[CURLOPT_POSTFIELDS] = $paramString; $curlOpts[CURLOPT_URL] .= strpos($curlOpts[CURLOPT_URL], '?') === false ? '?' : '&'; $curlOpts[CURLOPT_URL] .= 'instance=' . $params['instance']; } $curl = curl_init(); curl_setopt_array($curl, $curlOpts); $responseBody = $this->curlExec($curl); $responseInfo = $this->curlInfo($curl); if ($responseBody === false) { $responseBody = array('status' => 'error', 'message' => $this->curlError($curl)); } curl_close($curl); if ($responseInfo['content_type'] != 'application/json') { return $responseBody; } return json_decode($responseBody, true); }
public function execute() { $mh = curl_multi_init(); $conn = []; foreach ($this->getUrls() as $k => $url) { $this->setOption(CURLOPT_URL, $url); $ch = curl_init(); curl_setopt_array($ch, $this->getOptions()); $conn[$k] = $ch; curl_multi_add_handle($mh, $conn[$k]); } $active = false; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } $res = []; foreach ($this->getUrls() as $k => $url) { $res[$k] = curl_multi_getcontent($conn[$k]); curl_close($conn[$k]); curl_multi_remove_handle($mh, $conn[$k]); } curl_multi_close($mh); return $res; }
public static function sendRequest($host, array $fields, $method = 'get', $extra_curl = []) { $curl = curl_init(); switch (strtolower($method)) { case 'get': $curl_params = [CURLOPT_URL => $host . '?' . http_build_query($fields), CURLOPT_RETURNTRANSFER => 1] + $extra_curl; curl_setopt_array($curl, $curl_params); break; case 'post': $curl_params = [CURLOPT_POST => true, CURLOPT_URL => $host, CURLOPT_HTTPAUTH => CURLAUTH_ANY, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => false, CURLOPT_POSTFIELDS => http_build_query($fields)] + $extra_curl; curl_setopt_array($curl, $curl_params); break; } $result = curl_exec($curl); if (!$result) { throw new \Exception(curl_errno($curl)); } $json = json_decode($result, true); if ($json) { $output = $json; } else { parse_str($result, $output); } // if the result is not a valid json, it might be a string to be parsed if (isset($output['error'])) { //throw new \Exception( $output['error_message']); var_dump($output); exit; } return $output; }
/** * Perform InfluxDB request * * @param string $uri * @param Query $query * @param JsonSerializable $postData * * @return mixed */ public function request($uri, Query $query, JsonSerializable $postData = null) { $params = clone $query; $params->addQueryPart('u', $this->username); $params->addQueryPart('p', $this->password); $url = "http://{$this->host}:{$this->port}{$uri}?" . http_build_query($params->getArrayCopy()); $ch = curl_init($url); curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true)); if ($postData !== null) { curl_setopt_array($ch, array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($postData), CURLOPT_HTTPHEADER => array('Content-Type: application/json'))); } $response = curl_exec($ch); $info = curl_getinfo($ch); if ($info['http_code'] !== 200) { if ($response === false) { throw new Exception\InvalidApiResponse('Empty Response Body', $info['http_code']); } $result = json_decode($response, true); if (is_array($result) === false) { throw new Exception\InvalidApiResponse('Invalid Response Body', $info['http_code'], null, $response); } if (array_key_exists('error', $result) === true) { throw new Exception\ApiError($result['error']); } } // Decode result $result = json_decode($response, true); // Return results return $result['results']; }
function curlExec($base_url) { $ch = curl_init($base_url); curl_setopt_array($ch, array(CURLOPT_URL => $base_url, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_TIMEOUT => 30, CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)', CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0)); $results = curl_exec($ch); return $results; }
/** * Выполнить запрос * @param $command - команда * @param array $params - параметры команды * @return NssResponse */ public function request($command, array $params = []) { if (empty($this->ip)) { throw new InvalidParamException('IP not defined.'); } if (empty($this->port)) { throw new InvalidParamException('Port not defined.'); } $ch = curl_init($this->ip); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => 1, CURLOPT_PROXY => false, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CONNECTTIMEOUT => $this->connectTimeout, CURLOPT_PORT => $this->port, CURLOPT_POSTFIELDS => $this->createBody($command, $params)]); $this->answer = @curl_exec($ch); if (curl_errno($ch) || empty($this->answer)) { $this->answer = new NssResponse(); $this->answer->error = 'По техническим причинам функция недоступна. Попробуйте позже.'; Yii::error(curl_error($ch), 'nss-direct'); } else { $this->answer = @simplexml_load_string($this->answer); if ($this->answer === false) { $this->answer = new NssResponse(); $this->answer->error = 'От сервера пришел неверный ответ.'; } } curl_close($ch); return $this->answer; }
/** * shall be used beyond high level http connections unit tests (default parameters) * * @param string $url url to call * @param string $method * @param string $returnType CURLINFO_HTTP_CODE, etc... (default returns rhe http response data * @param array $curlOptions (numeric arrays get interpreted as headers) * @return mixed */ protected function curl($url, $method = CURLOPT_HTTPGET, $returnType = "data", $curlOptions = array()) { $options = $this->getDefaultCurlOptions(); if (!\tao_helpers_Array::isAssoc($curlOptions)) { $curlOptions = array(CURLOPT_HTTPHEADER => $curlOptions); } foreach ($curlOptions as $key => $value) { if (isset($options[$key]) && is_array($options[$key]) && is_array($value)) { $options[$key] = array_merge($options[$key], $value); } else { $options[$key] = $value; } } $process = curl_init($url); if ($method != "DELETE") { curl_setopt($process, $method, 1); } else { curl_setopt($process, CURLOPT_CUSTOMREQUEST, "DELETE"); } curl_setopt_array($process, $options); $data = curl_exec($process); if ($returnType != "data") { $data = curl_getinfo($process, $returnType); } curl_close($process); return $data; }
private static function sendRequest($request) { $t1 = microtime(true); $ch = curl_init(); $options = array(CURLOPT_USERAGENT => self::userAgent(), CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_HEADER => true, CURLOPT_NOBODY => false, CURLOPT_CUSTOMREQUEST => $request->method, CURLOPT_URL => $request->url); if (!empty($request->headers)) { $headers = array(); foreach ($request->headers as $key => $val) { array_push($headers, "{$key}: {$val}"); } $options[CURLOPT_HTTPHEADER] = $headers; } curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); if (!empty($request->body)) { $options[CURLOPT_POSTFIELDS] = $request->body; } curl_setopt_array($ch, $options); $result = curl_exec($ch); $t2 = microtime(true); $duration = round($t2 - $t1, 3); $ret = curl_errno($ch); if ($ret !== 0) { $r = new Response(-1, $duration, array(), null, curl_error($ch)); curl_close($ch); return $r; } $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = self::parseHeaders(substr($result, 0, $header_size)); $body = substr($result, $header_size); curl_close($ch); return new Response($code, $duration, $headers, $body, null); }
/** * {@inheritDoc} */ public function getContent($url) { if (!function_exists('curl_init')) { throw new ExtensionNotLoadedException('cURL has to be enabled.'); } $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_HEADER, 1); if ($this->timeout) { curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout); } if ($this->connectTimeout) { curl_setopt($c, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); } if ($this->userAgent) { curl_setopt($c, CURLOPT_USERAGENT, $this->userAgent); } if ($this->options && is_array($this->options) && count($this->options) > 0) { curl_setopt_array($c, $this->options); } $content = curl_exec($c); $headerSize = curl_getinfo($c, CURLINFO_HEADER_SIZE); curl_close($c); if (false === $content) { $this->setHeaders([]); return null; } $header = substr($content, 0, $headerSize); $this->setHeaders($this->parseHeader($header)); $body = substr($content, $headerSize); return $body; }
/** * CallApi * * @param endPoint $endPoint partial end point url * @param params $params to be passed to api * @return array response from api or general error form this class */ public function callApi($endPoint, array $params) { /* check if end point is available prior to make request */ if (!in_array($endPoint, $this->endPoints)) { if (Mage::getSingleton("core/session")->getPsonifyDebug() == 'true') { echo "<br/><h1>End Point</h1><br/>"; echo $endPoint; echo "<br/><h1>Sent Params</h1><br/>"; Zend_Debug::dump($params); echo "<br/><h1>Received Result</h1><br/>"; Zend_Debug::Dump($this->getValidationErrorResponse('End point is not valid')); } return $this->getValidationErrorResponse('End point is not valid'); } else { $params["token"] = isset($params["token"]) ? $params["token"] : $params["data"]["token"]; /* initializing curl */ $ch = curl_init(); $curlConfig = array(CURLOPT_URL => $this->apiUrl . '/' . $endPoint, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => json_encode($params)); curl_setopt_array($ch, $curlConfig); $result = curl_exec($ch); if (Mage::getSingleton("core/session")->getPsonifyDebug() == 'true') { echo "<br/><h1>End Point</h1><br/>"; echo $endPoint; echo "<br/><h1>Sent Params</h1><br/>"; Zend_Debug::dump($params); echo "<br/><h1>Recieved Result</h1><br/>"; Zend_Debug::Dump($result); } curl_close($ch); return json_decode($result); } }
/** * Fuction to make an HTTP call using curl * * @param String $subject Entity to perform action on * @param String $json JSON data to send on HTTP call * @param String $action The HTTP method to use * @return String */ function curl_wrap($subject, $json, $action) { $ch = curl_init(); curl_setopt_array($ch, array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 10)); switch ($action) { case "POST": curl_setopt($ch, CURLOPT_URL, 'https://' . domain . '.agilecrm.com/core/php/api/' . $subject . '?id=' . apikey); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); break; case "GET": $json = json_decode($json); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_URL, 'https://' . domain . '.agilecrm.com/core/php/api/' . $subject . '?id=' . apikey . '&email=' . $json->{'email'}); break; case "PUT": curl_setopt($ch, CURLOPT_URL, 'https://' . domain . '.agilecrm.com/core/php/api/' . $subject . '?id=' . apikey); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); break; case "DELETE": $json = json_decode($json); curl_setopt($ch, CURLOPT_URL, 'https://' . domain . '.agilecrm.com/core/php/api/' . $subject . '?id=' . apikey . '&email=' . $json->{'email'}); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); break; default: break; } curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset : UTF-8;')); curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 120)); $output = curl_exec($ch); curl_close($ch); return $output; }
/** * @param $method - API method, including version number * @param array $params - Query params * @param string $requestType - (get|post|put|delete) * @param string $format - (json|xml) * @param bool|true $isAuth * * @return mixed * @throws Exception * */ public function call($method, $params = array(), $requestType = 'get', $format = 'json', $isAuth = true) { if (!is_array($params)) { throw new Exception('Query params must be an array.'); } $type = strtoupper($requestType); if (!in_array($type, array('GET', 'POST', 'PUT', 'DELETE'))) { $type = 'GET'; } $params['format'] = $format; $options = array(CURLOPT_URL => $this->_url . $method, CURLOPT_CUSTOMREQUEST => $type, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_HEADERFUNCTION => array($this, '_parseHeaders')); $ch = curl_init(); if ($type == 'GET') { $options[CURLOPT_URL] = $this->_url . $method . '?' . http_build_query($params); } else { $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = http_build_query($params); } if ($isAuth) { $options[CURLOPT_HTTPHEADER] = $this->_getAuthHeader($method, $params); } curl_setopt_array($ch, $options); $response = curl_exec($ch); $error = curl_error($ch); $this->_httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($error) { throw new Exception($error); } return $response; }
/** * @inheritdoc */ public function request($action, array $getData = [], array $postData = []) { try { $curlOptions = [CURLOPT_RETURNTRANSFER => true]; if ($postData) { $json = json_encode($postData, JSON_PRETTY_PRINT); if ($json === false) { throw new RequesterException('Failed to serialize data into JSON. Data: ' . var_export($postData, true)); } $curlOptions = $curlOptions + [CURLOPT_POSTFIELDS => $json, CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Content-Length: ' . strlen($json)]]; } $getParams = $getData ? '?' . http_build_query($getData) : ''; $curl = curl_init($this->endpoint->getUrl() . $action . $getParams); curl_setopt_array($curl, $curlOptions); $result = curl_exec($curl); if ($result === false) { throw new RequesterException(sprintf('cURL error: [%d] %s', curl_errno($curl), curl_error($curl))); } $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); } catch (RequesterException $e) { throw $e; } catch (\Exception $e) { $result = empty($result) ? '' : ', result: ' . $result; throw new RequesterException('An error occurred during the transfer' . $result, null, $e); } if ($httpCode !== 200) { throw new RequesterException(sprintf("Request resulted in HTTP code '%d'. Response result:\n%s", $httpCode, $result)); } return new Response($result); }
public static function curlFetch($url = '', $http_post = false, $postData = array(), $curlOpts = array()) { $url = trim($url); if ($url == '') { return false; } # ======================================================== # Curl get/post to a specific url # ======================================================== $ch = curl_init(); if ($ch) { # init success! Now, set options $options = array(CURLOPT_URL => $url, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36', CURLOPT_ENCODING => 'gzip', CURLOPT_TIMEOUT => 15); $options = $curlOpts + $options; if ($http_post) { $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $postData; } curl_setopt_array($ch, $options); $res = curl_exec($ch); if (curl_errno($ch) == 0) { # request successful! Response is in $res curl_close($ch); return $res; } else { # request failed! curl_close($ch); return false; } } else { # curl init failed return false; } }
function login($email = null, $password = null) { //brian@sufferhub.com //BiteMe123! //set url for curl $url = "https://www.strava.com/api/v2/authentication/login"; //set post fields $fields = array('email' => urlencode($email), 'password' => urlencode($password)); foreach ($fields as $key => $value) { $fields_string .= $key . '=' . $value . '&'; } rtrim($fields_string, '&'); //set curl options $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $fields_string); //get curl results $ch = curl_init($url); curl_setopt_array($ch, $options); $content = curl_exec($ch); $err = curl_errno($ch); $errmsg = curl_error($ch); $header = curl_getinfo($ch); curl_close($ch); //decode result $data = json_decode($content); if (isset($data->token)) { //check if the authentication was a success //save auth data in a fsession $_SESSION['id'] = $data->athlete->id; $_SESSION['token'] = $data->token; return true; } else { return false; } }
/** * Executing curl request * @param array $additionalOptions * @return mixed */ protected function executeRequest(array $additionalOptions) { $cookiesPath = __DIR__ . DIRECTORY_SEPARATOR . self::COOKIES_FILE_NAME; $options = array_replace([CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEFILE => $cookiesPath, CURLOPT_COOKIEJAR => $cookiesPath], $additionalOptions); curl_setopt_array($this->ch, $options); return curl_exec($this->ch); }
public function __call($method, $args) { $args = count($args) && is_array($args[0]) ? $args[0] : array(); $curlopt = array(CURLOPT_USERPWD => sprintf("%s:%s", $this->user, $this->pass), CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HTTPHEADER => array('Expect:')); $uri = $this->uri ? sprintf("%s/%s", $this->uri, $method) : $method; if (array_key_exists('id', $args)) { $uri .= '/' . $args['id']; } unset($args['id']); $url = sprintf("%s.twitter.com/%s.%s", $method == 'search' ? 'search' : 'www', $uri, $this->format); if (in_array($method, array('new', 'create', 'update', 'destroy'))) { $curlopt[CURLOPT_POST] = TRUE; if ($args) { $curlopt[CURLOPT_POSTFIELDS] = $args; } } elseif ($args) { $url .= '?' . http_build_query($args); } $curl = curl_init($url); curl_setopt_array($curl, $curlopt); $data = curl_exec($curl); $meta = curl_getinfo($curl); curl_close($curl); if ($meta['http_code'] != 200) { throw new TwitterException("Response code: {$meta['http_code']} from \n\t{$url}"); } if ($this->format == 'json') { return json_decode($data); } return $data; }
/** * Returns the output of a remote URL. Any [curl option](http://php.net/curl_setopt) * may be used. * * // Do a simple GET request * $data = Remote::get($url); * * // Do a POST request * $data = Remote::get($url, array( * CURLOPT_POST => TRUE, * CURLOPT_POSTFIELDS => http_build_query($array), * )); * * @param string remote URL * @param array curl options * @return string * @throws Kohana_Exception */ public static function remote($url, array $options = NULL) { // The transfer must always be returned $options[CURLOPT_RETURNTRANSFER] = TRUE; // Open a new remote connection $remote = curl_init($url); // Set connection options if (!curl_setopt_array($remote, $options)) { throw new Kohana_Exception('Failed to set CURL options, check CURL documentation: :url', array(':url' => 'http://php.net/curl_setopt_array')); } // Get the response $response = curl_exec($remote); // Get the response information $code = curl_getinfo($remote, CURLINFO_HTTP_CODE); if ($code and $code < 200 or $code > 299) { $error = $response; } elseif ($response === FALSE) { $error = curl_error($remote); } // Close the connection curl_close($remote); if (isset($error)) { throw new Kohana_OAuth_Exception('Error fetching remote :url [ status :code ] :error', array(':url' => $url, ':code' => $code, ':error' => $error)); } return $response; }
/** * Make an api request * * @param string $resource * @param array $params * @param string $method */ public function call($resource, $params = array()) { $queryString = 'access_token=' . $this->getAccessToken(); if (!empty($params) && is_array($params)) { $queryString .= http_build_query($params); } $requestUrl = self::API_URL . $resource . '/?' . $queryString; $curl = curl_init(); $curl_options = array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $requestUrl, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => array('Accept: application/json', 'appid: nike')); curl_setopt_array($curl, $curl_options); $response = curl_exec($curl); $curl_info = curl_getinfo($curl); //@todo test for curl error if ($response === FALSE) { throw new Exception(curl_error($curl), curl_errno($curl)); } curl_close($curl); //@todo test for any non 200 response if ($curl_info['http_code'] != 200) { throw new Exception("Response: Bad response - HTTP Code:" . $curl_info['http_code']); } $jsonArray = json_decode($response); if (!is_object($jsonArray)) { throw new Exception("Response: Response was not a valid response"); } return $jsonArray; }
/** * Make API request * * @param string $method string API method to request * @param array $params Additional request parameters * @return array / boolean Response array / boolean false on failure */ public function request($method, $params = array()) { $this->_errors = array(); if (empty($method)) { //Check if API method is not empty $this->_errors = array('API method is missing'); return false; } //Our request parameters $requestParams = array('METHOD' => $method, 'VERSION' => $this->_version) + $this->_credentials; //Building our NVP string $request = http_build_query($requestParams + $params); //cURL settings $curlOptions = array(CURLOPT_URL => $this->_endPoint, CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $request); $ch = curl_init(); curl_setopt_array($ch, $curlOptions); //Sending our request - $response will hold the API response $response = curl_exec($ch); //Checking for cURL errors if (curl_errno($ch)) { $this->_errors = curl_error($ch); curl_close($ch); return false; //Handle errors } else { curl_close($ch); $responseArray = array(); parse_str($response, $responseArray); // Break the NVP string to an array return $responseArray; } }