Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. It's widely used in the PHP ecosystem for consuming REST APIs, interacting with other web services, or simply fetching web pages. Guzzle is built on top of PSR-7, PSR-18, and PSR-17 interfaces, ensuring interoperability with other PHP HTTP components.
Key features of Guzzle include:
* Simple Interface: Provides a straightforward API for making various types of HTTP requests (GET, POST, PUT, DELETE, etc.).
* Stream Support: Efficiently handles large uploads and downloads using PHP streams, avoiding memory exhaustion.
* Middleware System: A powerful and flexible system that allows you to inject custom logic into the request/response lifecycle. This is useful for tasks like logging, caching, authentication, retrying failed requests, and more.
* Asynchronous Requests: Supports making non-blocking HTTP requests using Promises, enabling concurrent request processing.
* Error Handling: Provides robust mechanisms for handling HTTP errors (e.g., 4xx, 5xx status codes) and network issues.
* Redirects and Cookies: Automatically handles HTTP redirects and manages cookies for persistent sessions.
* Proxies: Supports making requests through HTTP/HTTPS proxies.
* Extensible: Its design allows easy extension and customization to fit specific application needs.
Guzzle simplifies complex HTTP communication tasks, making it a go-to choice for developers building PHP applications that need to interact with external APIs or web resources.
Example Code
<?php
require 'vendor/autoload.php'; // Autoload files using Composer
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
// 1. Create a Guzzle client instance
// You can define a base_uri for all requests made with this client
$client = new Client([
'base_uri' => 'https://jsonplaceholder.typicode.com/', // A free fake API for testing and prototyping
'timeout' => 5.0, // Response timeout
]);
echo "--- Guzzle HTTP Client Examples ---\n\n";
// --- Example 1: Making a GET Request ---
echo "--- GET Request Example ---\n";
try {
$response = $client->request('GET', 'posts/1'); // Fetch post with ID 1
$statusCode = $response->getStatusCode(); // Get the status code
$body = $response->getBody(); // Get the response body as a stream
echo "GET Request Status: " . $statusCode . "\n";
echo "GET Request Body: " . $body . "\n\n";
// You can also get the body as a string directly
// echo "GET Request Body (as string): " . (string) $body . "\n\n";
// Or decode JSON if the content type is application/json
$data = json_decode((string) $body, true);
echo "Decoded GET Data Title: " . $data['title'] . "\n\n";
} catch (RequestException $e) {
echo "GET Request Failed!\n";
echo "Message: " . $e->getMessage() . "\n";
if ($e->hasResponse()) {
echo "Response Body: " . $e->getResponse()->getBody()->getContents() . "\n";
}
echo "\n";
}
// --- Example 2: Making a POST Request with JSON Body ---
echo "--- POST Request Example (JSON) ---\n";
try {
$newPost = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1,
];
$response = $client->request('POST', 'posts', [
'json' => $newPost, // Guzzle will automatically set Content-Type to application/json
]);
$statusCode = $response->getStatusCode();
$body = (string) $response->getBody();
echo "POST Request Status: " . $statusCode . "\n";
echo "POST Request Body: " . $body . "\n\n";
$createdPost = json_decode($body, true);
echo "Created Post ID: " . $createdPost['id'] . "\n\n";
} catch (RequestException $e) {
echo "POST Request Failed!\n";
echo "Message: " . $e->getMessage() . "\n";
if ($e->hasResponse()) {
echo "Response Body: " . $e->getResponse()->getBody()->getContents() . "\n";
}
echo "\n";
}
// --- Example 3: Making a POST Request with Form Parameters ---
echo "--- POST Request Example (Form Parameters) ---\n";
try {
$response = $client->request('POST', 'posts', [
'form_params' => [ // Guzzle will automatically set Content-Type to application/x-www-form-urlencoded
'title' => 'my form post',
'body' => 'This is a test post from form parameters.',
'userId' => 2,
]
]);
$statusCode = $response->getStatusCode();
$body = (string) $response->getBody();
echo "POST Form Request Status: " . $statusCode . "\n";
echo "POST Form Request Body: " . $body . "\n\n";
} catch (RequestException $e) {
echo "POST Form Request Failed!\n";
echo "Message: " . $e->getMessage() . "\n";
if ($e->hasResponse()) {
echo "Response Body: " . $e->getResponse()->getBody()->getContents() . "\n";
}
echo "\n";
}
// --- Example 4: Handling specific HTTP headers and different methods (e.g., PUT) ---
echo "--- PUT Request Example ---\n";
try {
$updatedPost = [
'id' => 1, // When updating, often the ID is part of the URL or body
'title' => 'updated title',
'body' => 'This post has been updated.',
'userId' => 1,
];
$response = $client->request('PUT', 'posts/1', [
'headers' => [
'User-Agent' => 'Guzzle/ExampleApp v1.0',
'Accept' => 'application/json',
],
'json' => $updatedPost,
]);
$statusCode = $response->getStatusCode();
$body = (string) $response->getBody();
echo "PUT Request Status: " . $statusCode . "\n";
echo "PUT Request Body: " . $body . "\n\n";
} catch (RequestException $e) {
echo "PUT Request Failed!\n";
echo "Message: " . $e->getMessage() . "\n";
if ($e->hasResponse()) {
echo "Response Body: " . $e->getResponse()->getBody()->getContents() . "\n";
}
echo "\n";
}
// --- Example 5: Sending an Asynchronous Request (non-blocking) ---
echo "--- Asynchronous GET Request Example ---\n";
// This is more advanced, for non-blocking operations.
// The promise is returned immediately, and you can "then" process the response later.
$promise = $client->getAsync('posts/2')->then(
function ($response) {
echo "Async GET Request Success!\n";
echo "Async Status: " . $response->getStatusCode() . "\n";
echo "Async Body: " . (string) $response->getBody() . "\n";
},
function ($exception) {
echo "Async GET Request Failed!\n";
echo "Async Message: " . $exception->getMessage() . "\n";
}
);
// Do other work while the request is in flight...
echo "Doing other work while async request is pending...\n";
// Wait for the request to complete. This is blocking until the promise is resolved.
$promise->wait();
echo "\n";
echo "--- Guzzle Examples Complete ---\n";
?>








guzzlehttp/guzzle