-
Notifications
You must be signed in to change notification settings - Fork 1
The Curl library
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.
Note: starting with v1.0.0 the
Curlclass 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 == trueand the response has the headerContent-Type: application/jsonthen 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.
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\Getimplements aGETrequest; -
SnooPHP\Curl\Postimplements aPOSTrequest; -
SnooPHP\Curl\Putimplements aPUTrequest; -
SnooPHP\Curl\Deleteimplements aDELETrequest;
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();