Skip to content
Greg Bowler edited this page Mar 28, 2023 · 5 revisions

cURL is a tool for transferring data to and from a server, and is widely available on most operating systems. It's most commonly used for making HTTP requests, such as downloading web pages, posting form data, or interacting with APIs.

PHP comes with bindings to libcurl, a library created by Daniel Stenberg, which directly calls the underlying C implementation in a very efficient manner.

This library wraps the PHP cURL functions with object oriented counterparts. The purpose is to ease the process of writing unit tests in other software that uses the library, along with normalising the way output is handled.

Output handling

The only change introduced by this library to how the native cURL functions work is output handling. By default, cURL functions will output data they receive directly to STDOUT. It's common to use the CURLOPT_RETURNTRANSFER option to change this behaviour, but this starts to become complicated when using multiple concurrent Curl handles within a CurlMulti object.

This library manages the incoming data buffer for you, normalising the method of accessing the response content into two functions:

  • output():string - returns the response body as a string.
  • outputJson():JsonObject - returns the response body as a pre-parsed JsonObject

A JsonObject provides type safe getter functions on the response, such as getString(), getBool(), etc. which is useful when working with well-formed JSON data.

$curl = new Curl("https://catfact.ninja/fact");
$curl->exec();
$json = $curl->outputJson();
echo "Here's a cat fact: {$json->getString("fact")}";
echo PHP_EOL;
echo "The fact's length is {$json->getInt("length")} characters.";
echo PHP_EOL;

Read more about the JSON library used at https://www.php.gt/json.

HTTP clients and Web Standards

This library was first conceived when work started on PHP.Gt/Fetch, a PHP implementation of the Fetch web standard.

Fetch is an asynchronous HTTP client, and it made perfect sense to utilise the bulletproof CurlMulti capabilities of libcurl, but using native PHP functions was difficult to unit test.

In conclusion, feel free to use this library for your project's HTTP requests, but the intention behind the project is simply to act as the internal data transfer tool within Fetch.


If you would like to learn more about this library, continue to Basic Curl usage.