FetchPHP is a PHP library that mimics the behavior of JavaScriptβs fetch
API using the powerful Guzzle HTTP client. FetchPHP supports both synchronous and asynchronous requests and provides an easy-to-use, flexible API for making HTTP requests in PHP.
To install FetchPHP, run the following command:
composer require jerome/fetch-php
FetchPHP provides three main functions:
fetch
β Performs a synchronous HTTP request.fetch_async
β Performs an asynchronous HTTP request and returns a GuzzlePromiseInterface
.fetchAsync
β An alias forfetch_async
, but deprecated.
By default, FetchPHP uses a singleton instance of the Guzzle client shared across all requests. However, you can provide your own Guzzle client through the options
parameter of both fetch
and fetch_async
. This gives you full control over the client configuration, including base URI, headers, timeouts, and more.
<?php
use GuzzleHttp\Client;
// Create a singleton instance of Guzzle client
$client = new Client([
'base_uri' => 'https://jsonplaceholder.typicode.com',
'timeout' => 10.0,
// Other default options
]);
// Pass the Guzzle client into the fetch function via options
$response = fetch('/todos/1', [
'client' => $client
]);
$response2 = fetch('/todos/2', [
'client' => $client
]);
print_r($response->json());
print_r($response2->json());
Passing a singleton Guzzle client is useful when:
- You're making many requests and want to avoid the overhead of creating a new client each time.
- You want to configure specific client-wide options (e.g., base URI, timeouts, headers) and reuse them across multiple requests.
The fetch
function performs an HTTP request and returns a Response
object, which provides convenient methods to interact with the response.
<?php
require 'vendor/autoload.php';
$response = fetch('https://jsonplaceholder.typicode.com/todos/1');
// Get the JSON response
$data = $response->json();
print_r($data);
// Get the status text (e.g., "OK")
echo $response->statusText();
The Response
class, now based on Guzzleβs Psr7\Response
, provides various methods to interact with the response data:
json(bool $assoc = true)
: Decodes the response body as JSON. If$assoc
istrue
, it returns an associative array. Iffalse
, it returns an object.text()
: Returns the response body as plain text.blob()
: Returns the response body as a PHP stream resource (like a "blob").arrayBuffer()
: Returns the response body as a binary string.statusText()
: Returns the HTTP status text (e.g., "OK" for200
).ok()
: Returnstrue
if the status code is between200-299
.isInformational()
,isRedirection()
,isClientError()
,isServerError()
: Helpers to check status ranges.
The fetch_async
function returns a PromiseInterface
object. You can use the .then()
and .wait()
methods to manage the asynchronous flow.
<?php
require 'vendor/autoload.php';
$promise = fetch_async('https://jsonplaceholder.typicode.com/todos/1');
$promise->then(function ($response) {
$data = $response->json();
print_r($data);
});
// Wait for the promise to resolve
$promise->wait();
You can handle errors with the then
or catch
methods of the promise:
$promise = fetch_async('https://nonexistent-url.com');
$promise->then(function ($response) {
// handle success
}, function ($exception) {
// handle failure
echo "Request failed: " . $exception->getMessage();
});
$promise->wait();
FetchPHP accepts an array of options as the second argument in both fetch
and fetch_async
. These options configure how the request is handled.
method
: HTTP method (e.g.,'GET'
,'POST'
,'PUT'
,'DELETE'
). Default is'GET'
.headers
: An array of HTTP headers (e.g.,['Authorization' => 'Bearer token']
).body
: Request body for POST, PUT, PATCH requests.json
: JSON data to send as the request body. Automatically setsContent-Type: application/json
.multipart
: An array of multipart form data for file uploads.query
: Associative array of query parameters.timeout
: Timeout in seconds. Default is10
.allow_redirects
: Whether to follow redirects (true
/false
). Default istrue
.cookies
: Boolean to enable cookies. Iftrue
, a newCookieJar
is used. You can also pass an instance ofGuzzleHttp\Cookie\CookieJar
.auth
: Array for HTTP Basic or Digest authentication.proxy
: Proxy server URL to route requests through.client
: A custom instance of Guzzle Client (e.g., singleton) to be reused for multiple requests.
<?php
$response = fetch('https://jsonplaceholder.typicode.com/posts', [
'method' => 'POST',
'json' => [
'title' => 'My Post',
'body' => 'This is the body of the post',
'userId' => 1,
],
]);
print_r($response->json());
<?php
$response = fetch('https://jsonplaceholder.typicode.com/posts', [
'query' => ['userId' => 1],
]);
print_r($response->json());
<?php
$response = fetch('https://example.com/upload', [
'method' => 'POST',
'multipart' => [
[
'name' => 'file',
'contents' => fopen('/path/to/file.jpg', 'r'),
'filename' => 'file.jpg'
],
]
]);
echo $response->statusText();
FetchPHP gracefully handles errors, returning a 500
status code and error message in the response when a request fails.
<?php
$response = fetch('https://nonexistent-url.com');
echo $response->getStatusCode(); // Outputs 500
echo $response->text(); // Outputs error message
<?php
$promise = fetch_async('https://nonexistent-url.com');
$promise->then(function ($
response) {
echo $response->text();
}, function ($exception) {
echo "Request failed: " . $exception->getMessage();
});
$promise->wait();
FetchPHP allows requests to be routed through a proxy server using the proxy
option:
<?php
$response = fetch('https://example.com', [
'proxy' => 'tcp://localhost:8080'
]);
echo $response->statusText();
You can specify HTTP Basic or Digest authentication using the auth
option:
<?php
$response = fetch('https://example.com/secure-endpoint', [
'auth' => ['username', 'password']
]);
echo $response->statusText();
The Response
class provides convenient methods for interacting with the response body, headers, and status codes.
json()
: Decodes the response body as JSON.text()
: Returns the raw response body as plain text.blob()
: Returns the body as a PHP stream (useful for file handling).arrayBuffer()
: Returns the body as a binary string.statusText()
: Returns the status text (e.g., "OK").ok()
: Returnstrue
if the status is 200β299.
<?php
$response = fetch('https://jsonplaceholder.typicode.com/todos/1');
// Get the response body as JSON
$data = $response->json();
print_r($data);
// Get the status text (e.g., "OK")
echo $response->statusText();
<?php
require 'vendor/autoload.php';
// POST request with JSON data, custom headers, query parameters, and authentication
$response = fetch('https://api.example.com/data', [
'method' => 'POST',
'headers' => [
'Authorization' => 'Bearer YOUR_TOKEN',
'Custom-Header' => 'MyHeaderValue'
],
'query' => ['param1' => 'value1'],
'json' => ['key' => 'value'],
'auth' => ['username', 'password'],
'timeout' => 10,
'allow_redirects' => true
]);
if ($response->ok()) {
// Print the JSON response
print_r($response->json());
} else {
echo "Error: " . $response->statusText();
}
This project is licensed under the MIT License - see the LICENSE.md file for details.
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repository and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/amazing-feature
) - Commit your Changes (
git commit -m 'Add some amazing-feature'
) - Push to the Branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- [Jerome Thayananthajothy] - Initial work - Thavarshan
See also the list of contributors who participated in this project.
- Hat tip to Guzzle HTTP for their Guzzle package, which provided the basis for this project.