Skip to content

The Curl library

Andrea Mecchia edited this page Jul 4, 2018 · 1 revision

Index > The Curl library


PHP supports the very popular libcurl library, which allows you to connect with different servers over different protocols.

SnooPHP Curl library is built on top of libcurl and provides an easy way to connect to a server over the HTTP protocol.

The Curl class

Note: starting with v1.0.0 the Curl class is no more abstract.

To connect to a server create a new instance of SnooPHP\Curl\Curl:

$curl = new Curl("https://www.google.com", [
	CURLOPT_CUSTOMREQUEST	=> "GET",
	CURLOPT_RETURNTRANSFER	=> true
]);

The signature of the constructor is Curl::__constructor(string $url, array $options = [], array $headers = [], $initOnly = true). $options is an array of curl options and $headers is an array of headers to send with the request.

When you create a new Curl object if $initOnly == true the connection is opened immediately, otherwise you must call Curl::exec() to start the transfer. We can then retrieve the result with Curl::content(bool $decodeJson = false):

$content = $curl->content();
echo $content;

If $decodeJson == true and the response has the header Content-Type: application/json then the json response will be converted in a PHP object

If for any reason the data transfer was not successful, content() will return null.

You can query the transfer status with Curl::success() and Curl::code(): the former returns true on success, the second returns the HTTP status code of the response:

if ($curl->success())
	echo $curl->content();
else
	Response::abort($curl->code(), "ERROR");

The Curl constructor offers great flexibility,but it doesn't hide the mechanisms of libcurl.

To perform simple GET, POST, PUT and DELETE requests we can use a static method which simplify the process, Curl::create(string $method, string $uri, string|array $data = "", array $headers = [], array $options = [], $initOnly = false):

$curl	= Curl::create("GET", "http://httpbin.org/get");
$curl	= Curl::create("POST", "http://httpbin.org/post", ["test" => "test"]);
$curl	= Curl::create("PUT", "http://httpbin.org/put", http_build_query(["test" => "test"])); 
$curl	= Curl::create("DELETE", "http://httpbin.org/delete");

You can still provide curl specific options if you desire.

Subclasses of Curl

Most of the time you'll find yourself performing very simple requests. In that case you may want to use one of the subclasses of Curl:

  • SnooPHP\Curl\Get implements a GET request;
  • SnooPHP\Curl\Post implements a POST request;
  • SnooPHP\Curl\Put implements a PUT request;
  • SnooPHP\Curl\Delete implements a DELET request;

The constructor of this classes is more minimalist w.r.t the Curl constructor and Curl::create() static method. You must provide the URL, the data to post/put, an optional array of headers and the $initOnly flag:

$curl = new Post("http://httpbin.org/post", ["test" => "test"]);
echo $curl->content();

Clone this wiki locally