/** * @param Request $request * @param bool $redirectsEnabled * @param int $maxRedirects * @return Response * @throws RequestException */ public function send(Request $request, $redirectsEnabled = false, $maxRedirects = 20) { /// Is there curl_init function if (!function_exists('curl_init')) { throw new RequestException('curl_init doesn\'t exists. Is curl extension instaled and enabled?'); } /// Dont send request without url if (!$request->getUrl()) { return new Response(); } $url = $request->getUrl(); if (!empty($this->params)) { $url .= '?' . http_build_query($this->params); } @curl_setopt($this->handle, CURLOPT_URL, $url); if ($request->getJSON() !== null) { $request->addHeaders(array('Content-Type' => 'application/json')); } $this->setCookies($request->getCookies()); $this->setHeaders($request->getHeaders()); $this->setMethod($request->getMethod()); /// Set post fields to CURL handle if (count($request->getPostFields()) > 0 || $request->getJSON()) { $fields = $request->getJSON() ? json_encode($request->getJSON()) : $request->getPostFields(); $this->setPostFields($fields, $request->getMethod(), $request->getHeader('Content-Type')); $request->setJSON(null); } /// Execute $response = curl_exec($this->handle); /// Remove content type header to not be used in further requests $request->unsetHeader('Content-Type'); /// Handle CURL error if ($response == FALSE) { throw new RequestException("CURL error [" . curl_errno($this->handle) . "]: " . curl_error($this->handle), curl_errno($this->handle)); } /// Separate response header and body /// Http 100 workaround $parts = explode("\r\n\r\nHTTP/", $response); $parts = (count($parts) > 1 ? 'HTTP/' : '') . array_pop($parts); list($headers, $body) = explode("\r\n\r\n", $parts, 2); $response = new Response(curl_getinfo($this->handle, CURLINFO_HTTP_CODE), $headers, $body); /// If cookiesEnabled then call addCookies with response cookies if ($request->isCookiesEnabled()) { $request->addCookies($response->getCookies()); } /// Are redirects enabled? (Also check redirects count) if ($redirectsEnabled && ($response->getCode() == 301 || $response->getCode() == 302 || $response->getCode() == 303) && $this->redirectCount < $maxRedirects) { $response = $this->doFollow($request, $response, $maxRedirects); } else { if ($this->redirectCount == $maxRedirects) { throw new RequestException("Maximum of " . $maxRedirects . " redirects reached."); } $this->redirectCount = 0; } return $response; }