function file_get_html_with_retry($url, $retrytimes = 5, $timeoutsec = 1) { global $errormsg; $errno = 0; for ($loopcount = 0; $loopcount < $retrytimes; $loopcount++) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeoutsec); curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutsec); curl_setopt($ch, CURLOPT_FAILONERROR, true); $contents = curl_exec($ch); //var_dump($contents); //debug if ($contents !== false) { curl_close($ch); break; } $errno = curl_errno($ch); $errormsg = curl_error($ch); print $timeoutsec; curl_close($ch); } if ($loopcount === $retrytimes) { $error_message = curl_strerror($errno); print 'http connection error : ' . $error_message . ' url : ' . $url . "\n"; } return $contents; }
/** * @param Request $request * @return Response */ public function call(Request $request) { // Create cURL $ch = curl_init(); // Set-up URL curl_setopt($ch, CURLOPT_URL, $request->getUrl()); // Set-up headers $headers = $request->getHeaders(); array_walk($headers, function (&$item, $key) { $item = "{$key}: {$item}"; }); curl_setopt($ch, CURLOPT_HTTPHEADER, array_values($headers)); // Set-up others curl_setopt_array($ch, $request->getOpts()); // Receive result $result = curl_exec($ch); // Parse response $response = new Response(); if ($result === FALSE) { $response->setError(curl_strerror(curl_errno($ch))); $response->setData(FALSE); $response->setCode(curl_errno($ch)); $response->setHeaders(curl_getinfo($ch)); } else { $response->setData(json_decode($result)); $response->setCode(curl_getinfo($ch, CURLINFO_HTTP_CODE)); $response->setHeaders(curl_getinfo($ch)); } // Close cURL curl_close($ch); return $response; }
/** * @param $uri * @param $target type of notification * @param $delay immediate, in 450sec or in 900sec * @param $messageId The optional custom header X-MessageID uniquely identifies a notification message. If it is present, the same value is returned in the notification response. It must be a string that contains a UUID * @param $message The message to send * * @throws PushException * @return array */ private function push($uri, $target, $delay, $messageId, $message) { $headers = array('Content-Type: text/xml', 'Accept: application/*', "X-NotificationClass: {$delay}"); if ($messageId != NULL) { $headers[] = "X-MessageID: {$messageId}"; } if ($target != NULL) { $headers[] = "X-WindowsPhone-Target:{$target}"; } $request = curl_init(); curl_setopt($request, CURLOPT_HEADER, true); curl_setopt($request, CURLOPT_HTTPHEADER, $headers); curl_setopt($request, CURLOPT_POST, true); curl_setopt($request, CURLOPT_POSTFIELDS, $message); curl_setopt($request, CURLOPT_URL, $uri); curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($request); if ($errorNumber = curl_errno($request)) { $errorMessage = curl_strerror($errorNumber); throw new PushException($errorMessage, $errorNumber); } curl_close($request); $result = array(); foreach (explode("\n", $response) as $line) { $tab = explode(":", $line, 2); if (count($tab) == 2) { $result[$tab[0]] = trim($tab[1]); } } return $result; }
public function crudAction($action = 'create') { switch ($action) { case 'create': curl_setopt($this->curlHandler, CURLOPT_CUSTOMREQUEST, "POST"); break; case 'update': curl_setopt($this->curlHandler, CURLOPT_CUSTOMREQUEST, "PUT"); break; case 'read': curl_setopt($this->curlHandler, CURLOPT_CUSTOMREQUEST, "GET"); break; case 'delete': curl_setopt($this->curlHandler, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } if (!empty($this->jsonData)) { curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS, $this->jsonData); } curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($this->jsonData))); $this->apiReponse = curl_exec($this->curlHandler); if ($errno = curl_errno($this->curlHandler)) { $error_message = curl_strerror($errno); echo "cURL error ({$errno}):\n {$error_message}"; } curl_close($this->curlHandler); }
public static function post($url, $postFields = null, $headers = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields); if (self::$readTimeout) { curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout); } if (self::$connectTimeout) { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout); } // https request if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if (is_array($headers) && 0 < count($headers)) { $httpHeaders = self::getHttpHearders($headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); } $httpResponse = new HttpResponse(); $httpResponse->setBody(curl_exec($ch)); $httpResponse->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE)); if ($errno = curl_errno($ch)) { throw new Exception(curl_strerror($errno)); } curl_close($ch); return $httpResponse->getBody(); }
public function connect() { $this->open(); $sendData = $this->serializeParams($this->getParameters()); curl_setopt($this->curl, CURLOPT_URL, "{$this->url}?{$sendData}"); //curl_setopt($this->curl, CURLOPT_POST, true); // HTTP POST //curl_setopt($this->curl, CURLOPT_POSTFIELDS, $sendData); $response = curl_exec($this->curl); if ($response === false) { $errno = @curl_errno($this->curl); $error = @curl_strerror($errno); $this->close(); throw TransferException::couldNotTransferData($this->url . ($this->isProxy() ? ' (usando proxy)' : ''), "[{$errno}] {$error}"); } list($response_headers_str, $response) = explode("\r\n\r\n", $response); /*$response_headers = $this->_readHeaders($response_headers_str); if (!$this->checkResponseToken($response_headers['X-FW-Response'])) { throw new WrongDataTransferException('Resposta inv�lida do servidor, entre em contato com a Furac�o'); }*/ $this->close(); if (empty($response)) { throw TransferException::emptyDataReturned(); } return $response; }
public function getErrorMessage() { if ($this->errNo) { return curl_strerror($this->errNo); } return null; }
/** * @param string|null $message */ public function __construct(RequestInterface $request, Response $response, $message = null) { $this->request = $request; $this->response = $response; if ($message === null) { $curlError = $response->getHeader('X-Curl-Error-Result'); $message = sprintf('HTTP %s request to "%s%s" failed: %d - "%s".', $request->getMethod(), $request->getHost(), $request->getResource(), $curlError ?: $response->getStatusCode(), $curlError ? curl_strerror($curlError) : $response->getReasonPhrase()); } parent::__construct($message); }
/** * createResultCollection. * * @param bool $hasError */ public function createResultCollection($hasError = false) { $errorLog = null; if ($hasError) { $errorLog = curl_strerror(5); } $result = new Result($this->createUrlInfo(), $hasError ? 400 : 200, 0.42, $errorLog); $resultCollection = new ResultCollection(); $resultCollection->append($result); return $resultCollection; }
private function execute($curl) { $body = curl_exec($curl); if ($errno = curl_errno($curl)) { $error_message = curl_strerror($errno); throw new HttpException("cURL error ({$errno}): {$error_message}", 0, $this->url); } $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE); curl_close($curl); return array($statusCode, $contentType, $body); }
/** * Performs Aspose Api Request. * * @param string $url Target Aspose API URL. * @param string $method Method to access the API such as GET, POST, PUT and DELETE * @param string $headerType XML or JSON * @param string $src Post data. * @param string $returnType * @return string * @throws Exception */ public static function processCommand($url, $method = 'GET', $headerType = 'XML', $src = '', $returnType = 'xml') { $dispatcher = AsposeApp::getEventDispatcher(); $method = strtoupper($method); $headerType = strtoupper($headerType); AsposeApp::getLogger()->info("Aspose Cloud SDK: processCommand called", array('url' => $url, 'method' => $method, 'headerType' => $headerType, 'src' => $src, 'returnType' => $returnType)); $session = curl_init(); curl_setopt($session, CURLOPT_URL, $url); if ($method == 'GET') { curl_setopt($session, CURLOPT_HTTPGET, 1); } else { curl_setopt($session, CURLOPT_POST, 1); curl_setopt($session, CURLOPT_POSTFIELDS, $src); curl_setopt($session, CURLOPT_CUSTOMREQUEST, $method); } curl_setopt($session, CURLOPT_HEADER, false); if ($headerType == 'XML') { curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/' . $returnType . '', 'Content-Type: application/xml', 'x-aspose-client: PHPSDK/v1.0')); } else { curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'x-aspose-client: PHPSDK/v1.0')); } curl_setopt($session, CURLOPT_RETURNTRANSFER, true); if (preg_match('/^(https)/i', $url)) { curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false); } // Allow users to register curl options before the call is executed $event = new ProcessCommandEvent($session); $dispatcher->dispatch(ProcessCommandEvent::PRE_CURL, $event); $result = curl_exec($session); $headers = curl_getinfo($session); if (substr($headers['http_code'], 0, 1) != '2') { if (curl_errno($session) !== 0) { throw new AsposeCurlException(curl_strerror(curl_errno($session)), $headers, curl_errno($session)); AsposeApp::getLogger()->warning(curl_strerror(curl_errno($session))); } else { throw new Exception($result); AsposeApp::getLogger()->warning($result); } } else { if (preg_match('/You have processed/i', $result) || preg_match('/Your pricing plan allows only/i', $result)) { AsposeApp::getLogger()->alert($result); throw new Exception($result); } } // Allow users to alter the result $event = new ProcessCommandEvent($session, $result); /** @var ProcessCommandEvent $dispatchedEvent */ $dispatchedEvent = $dispatcher->dispatch(ProcessCommandEvent::POST_CURL, $event); curl_close($session); // TODO test or the Event result needs to be returned in case an listener was triggered return $dispatchedEvent->getResult(); }
/** * Curl request to giving url * * @param string $url * @param array $param * * @return array */ public function sendRequest($url, $param) { $curl = curl_init($url); curl_setopt_array($curl, array(CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $param)); $getResult = curl_exec($curl); if ($errno = curl_errno($curl)) { $message = curl_strerror($errno); throw new CurlErrorException("CURL error : {$message}"); } curl_close($curl); parse_str($getResult, $result); return $result; }
/** * Process API requests to github and packagist * * @param $url * @param array $headers * @return mixed */ private static function doRequest($url, $headers = []) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $response = curl_exec($ch); if (0 !== ($errno = curl_errno($ch))) { $errorMessage = curl_strerror($errno); Yii::$app->session->setFlash("cURL error ({$errno}):\n {$errorMessage}"); } curl_close($ch); return $response; }
/** * @param array $messages - array of [$request, $response] * @param string|null $errorMessage */ public function __construct(array $messages, $errorMessage = null) { $this->messages = $messages; $errorMessages = []; if ($errorMessage === null) { foreach ($this->messages as $messages) { /** @var RequestInterface $request */ /** @var Response $response */ list($request, $response) = $messages; $curlError = $response->getHeader('X-Curl-Error-Result'); $errorMessages[] = sprintf('%s "%s%s": %d - "%s"', $request->getMethod(), $request->getHost(), $request->getResource(), $curlError ?: $response->getStatusCode(), $curlError ? curl_strerror($curlError) : $response->getReasonPhrase()); } $errorMessage = sprintf("Batch HTTP requests failed.\n - %s.", implode("\n - ", $errorMessages)); } list($request, $response) = current($this->messages); parent::__construct($request, $response, $errorMessage); }
public function testCurlErrors() { $expectedErrorCodeByDomain = array('' => CURLE_URL_MALFORMAT, 'foo://bar' => CURLE_UNSUPPORTED_PROTOCOL, 'http://non-existing-domain' => CURLE_COULDNT_RESOLVE_HOST, 'https://expired.badssl.com' => CURLE_SSL_CACERT); foreach ($expectedErrorCodeByDomain as $domain => $expectedErrorCode) { try { $this->connection->get($domain, []); } catch (ErrorException $e) { $expectedErrorMessage = 'cURL error ' . $expectedErrorCode; if (function_exists('curl_strerror')) { $expectedErrorMessage .= ' (' . curl_strerror($expectedErrorCode) . ')'; } $this->assertEquals($expectedErrorMessage, $e->getMessage()); continue; } $this->fail('An expected exception has not been raised'); } }
/** * Download a URL into a file. * * @param $source {String} * url to download. * @param $dest {String} * path to destination. * @param $showProgress {Boolean} * default true. * output progress to STDERR. * @return {Boolean} false if $dest already exists, true if created. */ function downloadURL($source, $dest, $showProgress = true) { if (file_exists($dest)) { return false; } if ($showProgress) { echo 'Downloading "' . $source . '"' . PHP_EOL; } $curl = curl_init(); $file = fopen($dest, 'wb'); curl_setopt_array($curl, array(CURLOPT_URL => $source, CURLOPT_FILE => $file, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_NOPROGRESS => $showProgress ? 0 : 1)); curl_exec($curl); $errno = curl_errno($curl); curl_close($curl); fclose($file); if ($errno) { unlink($dest); throw new Exception('Unable to download, errno=' . $errno . ' (' . curl_strerror($errno) . ')'); } return true; }
/** * @param string $link * @param array $options * @return string */ public function getRaw($link, $options = []) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $link); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); foreach ($options as $option => $value) { curl_setopt($ch, $option, $value); } $response = curl_exec($ch); $errno = curl_errno($ch); if ($errno) { $errorMessage = curl_strerror($errno); $exeptionMessage = "cURL error ({$errno}):\n {$errorMessage}"; throw new RemoteServerException($exeptionMessage); } elseif (curl_error($ch) !== '') { throw new RemoteServerException('Cannot get an information'); } return $response; }
public static function run($url, $xml, $json = 1) { // $url = 'http://123.231.241.42:8280/'.$url; //$url = 'http://123.231.241.42:8281/PROD/'.$url; // IP lokal production //$url = 'http://192.168.0.35:8280/PROD/'.$url; // IP international production // $url = 'http://123.231.241.42:8281/PROD/'.$url; //$url = 'https://tbs.webservices.visibleresults.net/LLWebService/'.$url; $url = Efiwebsetting::getData('LL_URL') . $url; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, "{$xml}"); $result = curl_exec($ch); // Check for errors and display the error message if ($errno = curl_errno($ch)) { $error_message = curl_strerror($errno); // echo "cURL error ({$errno}):\n {$error_message}"; $json['status_code'] = 0; $json['status_message'] = Efiwebsetting::getData('Constant_ll_failed'); echo json_encode($json); die; } curl_close($ch); if ($json == 1) { return Request::toJson($result, 0); } elseif ($json == 2) { return simplexml_load_string($result); } elseif ($json == 3) { $xmlDoc = new DOMDocument(); $xmlDoc->load($result); return $xmlDoc; } else { return $result; } }
function grabHTML($url) { $ch = curl_init(); $header = array('GET /1575051 HTTP/1.1', "Host: query.yahooapis.com", 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:en-US,en;q=0.8', 'Cache-Control:max-age=0', 'Connection:keep-alive', 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, $f = fopen(__DIR__ . "/error.log", "w+")); $returnHTML = curl_exec($ch); if ($errno = curl_errno($ch)) { $error_message = curl_strerror($errno); echo "cURL error ({$errno}):\n {$error_message}"; } curl_close($ch); return $returnHTML; }
/** * run. * * @return array */ public function run() { $urls = $this->urlProvider->getUrls(); $client = $this->client; //This is a bit messie, need a refacto $resultCollection = new ResultCollection(); $requests = function () use($urls, $client, $resultCollection) { foreach ($urls as $url) { (yield function () use($client, $url, $resultCollection) { return $client->sendAsync(new Request($url->getMethod(), $url->getUrl(), $url->getHeaders()), ['timeout' => $url->getTimeout(), 'connect_timeout' => $url->getTimeout(), 'on_stats' => function (TransferStats $tranferStats) use($url, $resultCollection) { $handlerError = null; $validatorError = null; $validatorResult = null; if ($tranferStats->hasResponse()) { $validatorResult = $url->getValidator()->check((string) $tranferStats->getResponse()->getBody()); if (false === $validatorResult) { $validatorError = $url->getValidator()->getError(); } $statusCode = $tranferStats->getResponse()->getStatusCode(); $transferTime = $tranferStats->getTransferTime(); } else { // If we have a connection error $statusCode = 400; $transferTime = 0; $handlerError = curl_strerror($tranferStats->getHandlerErrorData()); } $resultCollection->offsetSet($url->getName(), new Result($url, $statusCode, $transferTime, $handlerError, $validatorResult, $validatorError)); }]); }); } }; $pool = new Pool($this->client, $requests(), ['concurrency' => 5]); $promise = $pool->promise(); $promise->wait(); return $resultCollection; }
private function curl($url, $method = 'get') { // 创建一个cURL资源 $ch = curl_init($url); // 设置URL和相应的选项 curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($method == 'post') { curl_setopt($ch, CURLOPT_POST, 1); } // 抓取URL并把它传递给浏览器 $rs = curl_exec($ch); if ($rs === false) { if ($errno = curl_errno($ch)) { $error_message = curl_strerror($errno); echo "cURL error ({$errno}):\n {$error_message}"; } } else { //echo '正常'; } // 关闭cURL资源,并且释放系统资源 curl_close($ch); return $rs; }
/** * Starts a HTTP request via cURL * * @return string The response of the request */ private static function getCurl() { $args = func_get_args(); $args = count($args) > 1 ? $args : array_shift($args); $uri = $args[0]; $options = $args[1]; $callback = $args[2]; $ch = curl_init($uri); curl_setopt_array($ch, $options['curl']); if ($callback) { curl_setopt_array($ch, [CURLOPT_NOPROGRESS => false, CURLOPT_PROGRESSFUNCTION => ['self', 'progress']]); } $response = curl_exec($ch); if ($errno = curl_errno($ch)) { $error_message = curl_strerror($errno); throw new \RuntimeException("cURL error ({$errno}):\n {$error_message}"); } curl_close($ch); return $response; }
/** * Return string describing the given error code * @see http://php.net/manual/en/function.curl-strerror.php Official PHP documentation for curl_strerror() * @param int $errornum One of the [cURL error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) constants * @return string Returns error description or NULL for invalid error code. */ public static function strerror($errornum) { return curl_strerror($errornum); }
private function processMessages() { while ($done = curl_multi_info_read($this->mh)) { $id = (int) $done['handle']; if (!isset($this->handles[$id])) { // Probably was cancelled. continue; } $entry = $this->handles[$id]; $entry['response']['transfer_stats'] = curl_getinfo($done['handle']); if ($done['result'] !== CURLM_OK) { $entry['response']['curl']['errno'] = $done['result']; if (function_exists('curl_strerror')) { $entry['response']['curl']['error'] = curl_strerror($done['result']); } } $result = CurlFactory::createResponse($this, $entry['request'], $entry['response'], $entry['headers'], $entry['body']); $this->removeProcessed($id); $entry['deferred']->resolve($result); } }
private function hash_call($methodName, $nvpStr) { // declaring of global variables $subject = ''; $AUTH_token = ''; $AUTH_signature = ''; $AUTH_timestamp = ''; $API_Endpoint = $this->api_endpoint; $version = $this->version; $API_UserName = $this->api_username; $API_Password = $this->api_password; $API_Signature = $this->api_signature; // form header string $nvpheader = $this->nvpHeader(); // setting the curl parameters. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $API_Endpoint); curl_setopt($ch, CURLOPT_VERBOSE, 1); // turning off the server and peer verification(TrustManager Concept). curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); // in case of permission APIs send headers as HTTPheaders if (!empty($AUTH_token) && !empty($AUTH_signature) && !empty($AUTH_timestamp)) { $headers_array[] = "X-PP-AUTHORIZATION: " . $nvpheader; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array); curl_setopt($ch, CURLOPT_HEADER, false); } else { $nvpStr = $nvpheader . $nvpStr; } // check if version is included in $nvpStr else include the version. if (strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr)) { $nvpStr = "&VERSION=" . urlencode($version) . $nvpStr; } $nvpreq = "METHOD=" . urlencode($methodName) . $nvpStr; // setting the nvpreq as POST FIELD to curl curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); // var_dump($nvpreq);die(); // getting response from server $try_times = 3; do { $response = curl_exec($ch); $error_no = curl_errno($ch); if (!$error_no || $response) { break; } /* if ($error_no == 60) { curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); $response = curl_exec($ch); $error_no = curl_errno($ch); if (!$error_no || $response) { break; } } */ } while ((!$error_no || !$response) && $try_times--); // convrting NVPResponse to an Associative Array $nvpResArray = $this->deformatNVP($response); $nvpReqArray = $this->deformatNVP($nvpreq); //和上面那货不同的 if (curl_errno($ch)) { var_dump(curl_errno($ch)); var_dump(curl_error($ch)); var_dump(curl_strerror(7)); die; return false; } else { // closing the curl curl_close($ch); } return $nvpResArray; }
/** * @param resource $curlHandle * @return DefaultConnectionResponse * @throws Exception */ private function executeCurlHandle($curlHandle) { $multiHandle = $this->getCurlMultiHandle(); curl_multi_add_handle($multiHandle, $curlHandle); $running = null; do { $status = curl_multi_exec($multiHandle, $running); if ($status > CURLM_OK) { $errorMessage = 'cURL error ' . $status; if (function_exists('curl_multi_strerror')) { $errorMessage .= ' (' . curl_multi_strerror($status) . ')'; } throw new ErrorException($errorMessage); } $info = curl_multi_info_read($multiHandle); if ($info && isset($info['result']) && $info['result'] != CURLE_OK) { $errorMessage = 'cURL error ' . $info['result']; if (function_exists('curl_strerror')) { $errorMessage .= ' (' . curl_strerror($info['result']) . ')'; } throw new ErrorException($errorMessage); } curl_multi_select($multiHandle); } while ($running > 0); $content = curl_multi_getcontent($curlHandle); $headerSize = curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE); $httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); curl_multi_remove_handle($multiHandle, $curlHandle); $httpHeaderHelper = new HttpHeaderHelper(); $headers = $httpHeaderHelper->parseRawHeaders(explode("\r\n", substr($content, 0, $headerSize))); $body = substr($content, $headerSize); return new DefaultConnectionResponse($httpCode, $headers, $body); }
function recv($callback = NULL, $timeout = 0.1) { $active = 0; /* A reference to a flag to tell whether the cURLs are still running */ $t1 = $t2 = microtime(true); if ($this->count < 1) { return cy_dt(1, 'empty handle.'); } $errno = curl_multi_exec($this->mh, $active); if ($errno != CURLM_OK) { return cy_dt($errno, curl_strerror($errno)); } $select_func = function_exists('cy_curl_multi_select') ? 'cy_curl_multi_select' : 'curl_multi_select'; while ($this->count === $active && $t2 - $t1 < $timeout) { //$ready = $select_func($this->mh, $timeout, 0x01|0x4); $ready = curl_multi_select($this->mh, $timeout); if ($ready < 0) { return cy_dt(-1, 'curl_multi_select error'); } $errno = curl_multi_exec($this->mh, $active); if ($errno != CURLM_OK) { return cy_dt($errno, curl_strerror($errno)); } $t2 = microtime(true); } $data = []; while ($r = curl_multi_info_read($this->mh, $msgs_in_queue)) { $ch = $r['handle']; list(, $c, $key) = $this->handles[(int) $ch]; $data[$key] = $mix = $this->mix($ch, $c); if ($callback) { call_user_func($callback, $key, $mix); } } return cy_dt(OK, $data); }
/** * Starts a HTTP request via cURL * * @return string The response of the request */ private static function getCurl() { $args = func_get_args(); $args = count($args) > 1 ? $args : array_shift($args); $uri = $args[0]; $options = $args[1]; $callback = $args[2]; $ch = curl_init($uri); $response = static::curlExecFollow($ch, $options, $callback); $errno = curl_errno($ch); if ($errno) { $error_message = curl_strerror($errno); throw new \RuntimeException("cURL error ({$errno}):\n {$error_message}"); } curl_close($ch); return $response; }
public function getRequest($url) { // echo "URL: " . $url; $c = curl_init(); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_TIMEOUT, BulkSMS::$HTTP_TIMEOUT); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_USERAGENT, BulkSMS::$USER_AGENT); curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); /* Make the request and check the result. */ $content = curl_exec($c); $status = curl_getinfo($c, CURLINFO_HTTP_CODE); if ($errno = curl_errno($c)) { $error_message = curl_strerror($errno); echo "cURL error ({$errno}):\n {$error_message}\n"; } if ($status != 200) { throw new Exception(sprintf('Unexpected HTTP return code %d\\n' . $content, $status)); } return $content; }
public static function createToken($email = null, $password = null) { $owner_API = "https://owner-api.teslamotors.com/oauth/token"; $portal_API = "https://owner-api.teslamotors.com/api/1/vehicles"; $json = array("grant_type" => "password", "client_id" => "e4a9949fcfa04068f59abb5a658f2bac0a3428e4652315490b659d5ab3f35a9e", "client_secret" => "c75f14bbadc8bee3a7594412c31416f8300256d7668ea7e6e7f06727bfb9d220", "email" => $email, "password" => $password); $data = json_encode($json); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $owner_API); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $response = curl_exec($ch); $error = curl_error($ch); $errno = curl_errno($ch); curl_close($ch); if ($response === false) { log::add('tesla', 'Error', $error); throw new Exception(__($error, __FILE__)); } if ($errno) { throw new Exception(__("Curl Error : " . curl_strerror($errno), __FILE__)); } if (json_decode($response)->{'access_token'} == null) { if (json_decode($response)->{'reponse'} != null) { throw new Exception(__(json_decode($response)->{'response'}, __FILE__)); } else { throw new Exception(__(json_decode($response)->{'error'} . " - " . json_decode($response)->{'error_description'}, __FILE__)); } } return json_decode($response)->{'access_token'}; }