How to convert cUrl code to drupal way?

by Julia   Last Updated April 16, 2018 05:07 AM

I have below code

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
curl_close($ch);

In Drupal 8 way we can use

$client = \Drupal::httpClient();

$response = $client->request('GET', $url, [
  // To add 
]);

Not sure how to pass needed parameters/convert it to drupal way.

Tags : 8


Answers 1


The only special thing I see there is getting the effective URL, which is actually something that was specifically added back to Guzzle 6 for Drupal: https://github.com/guzzle/guzzle/issues/1166

See \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher::fetch:

  /** @var \Psr\Http\Message\UriInterface $actual_uri */
  $actual_uri = NULL;
  $response = $this->httpClientFactory->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);
Berdir
Berdir
April 16, 2018 06:13 AM

Related Questions