Translate cURL request to Guzzle

aran picture aran · Jul 31, 2015 · Viewed 7.3k times · Source

I am trying to use Guzzle instead of directly using cURL to achieve and HTTP request. How do I make this same type of request but with Guzzle? Or should I just stick to cURL?

$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");

Here is how for I have got. I keep running into 401 Unauthorized error. I know I have correct credentials. What makes me think I am not on the right track is the Guzzle docs stating: auth is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned. But from my understanding Guzzle defaults with cURL.

$guzzleData = [
  'auth' => [$token, 'X'],
  'allow_redirects' => true,
  'verify' => false,
];

$client = new \Guzzle\Http\Client();
$request = $client->get($url, $guzzleData);
$response = $request->send();

Answer

aran picture aran · Jul 31, 2015

Here is the solution:

$client = new \Guzzle\Http\Client();
$request = $client->get($url);

$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER, true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION, true);
$request->getCurlOptions()->set(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$request->getCurlOptions()->set(CURLOPT_USERPWD, "$token:X");

$response = $request->send();