imabdullah
imabdullah

Reputation: 347

How to use Guzzle HTTP Client in simple PHP?

I am currently using PHP CURL but somehow it is not working for basicAUTH in my case. I want to use guzzel HTTP client in simple PHP project (not a Laravel project). Every solution on the internet I found is setting up in laravel and installing it via composer.

$client = new \GuzzleHttp\Client();
$response = $client->post($service_url, [
    'auth' => [
        $username, 
        $admin_password
    ]
]);

or if guzzel do not works with simple PHP, Suggest other client which can work with simple PHP for basic Auth. Thanks

Upvotes: 2

Views: 8692

Answers (2)

Gad Iradufasha
Gad Iradufasha

Reputation: 161

First of all you need to navigate to your main forder you will be working in, which reside inside htdocs as usual and then insall GuzzleHttpClient by using composer tool

(Recommended: 2+ version)

composer require guzzlehttp/guzzle

It will download and install dependencies such as:

  • symfony/deprecation-contracts
  • psr/http-message
  • psr/http-client
  • guzzlehttp/promises
  • ralouphie/getallheaders, etc.

After getting it fully installed; try simple example to see if it really works

<?php
// First of all require autoload from vendor dir;
require_once "vendor/autoload.php";
use GuzzleHttp\Client;
  
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);
  
// The response to get
$res = $client->request('GET', '/api/users', [
    'query' => ['page' => '2', ]
]);
  
$body = $res->getBody();
$array_body = json_decode($body);
print_r($array_body);

?>

Check the result in the browser

Upvotes: 3

DonCallisto
DonCallisto

Reputation: 29932

Composer has nothing to do with Laravel or Guzzle, is "just" a package manager.
You can use - and I suggest to do so - composer in your project even if you're not using a framework.

Said that, once you have Guzzle source code (via composer or downloading directly the code; I would not reccommend the latter) you can just use it everywhere.

By the way I would suggest to use composer for two (main) reasons:

  • You can keep under control dependencies (like Guzzle) in order to update/downgrade them easily. Also composer will track possible conflicts with other dependencies (that for instance can't work together under some circumstances)
  • Composer has its own psr-4 autoloader

So yes, you can use Guzzle also without a framework and without composer, there's nothing preventing you to do so.

Upvotes: 0

Related Questions