4

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.

[UPDATE]

$uri = 'http://domain.com';

$client = \Drupal::httpClient();

$actual_uri = NULL;
$response = $client->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, \Psr\Http\Message\UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);

dump($response);
exit;
4

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);
  • Gives InvalidArgumentException: URI must be a string or UriInterface in GuzzleHttp\Psr7\uri_for() . Passing my URL in $request – Julia Apr 16 '18 at 6:43
  • well, what is your $url? apparently it's not a string which would not have worked for curl either – Berdir Apr 16 '18 at 7:01
  • Update your question with your updated code – Berdir Apr 16 '18 at 7:02
  • I have added code in question – Julia Apr 16 '18 at 7:08
  • your code snippet doesn't show where $request is coming from, fromOptions() is also called on the factory, which is a separate service. Have a look at the full method of the class I mentioned – Berdir Apr 16 '18 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.