cURL

cURL is a PHP extension, that allows to send and receive information via the URL syntax. By doing so, cURL makes it easy to communicate between different websites and domains.

Quantum's Curl library build on top of php-curl-class/php-curl-class library and makes easy to use the whole power of cURL.

To start using the Curl library first make it available in your controller.


use Quantum\Libraries\Curl\Curl;

        

The next code block shows how to set options, execute and fetche the result


$curl = (new Curl())
    ->setOptions([
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_NOBODY => true,
        CURLOPT_HEADER => 1,
    ])
    ->run('https://httpbin.org/get');

// out($curl->getResponseBody(), 1);

// out($curl->getResponseHeaders(), 1);

// out($curl->getErrors(), 1);

        

The following methods are availble in Curl library

  • setOptions() - The method sets the cURL options (the full list of options available here)
  • setHeaders() - The method sets the cURL headers.
  • run() - The method runs the cURL and can accept $url argument.
  • getResponseBody() - The method returns the body of response.
  • getResponseHeaders() - The method returns the headers of response.
  • getErrors() - The method returns error if occurred.

You can access to php-curl-class methods also. Below described the most common shorthand methods, the full list of available method can be found here. It's possible to chain several methods at the same time.

The shorthand method head() returns only the headers.


$curl = (new Curl())->head('https://httpbin.org/get');

out($curl->getResponseHeaders(), 1);

        

The shorthand method get() allows to send GET requests.


$curl = (new Curl())
    ->setHeaders(['CB-VERSION' => '2016-01-01'])
    ->get('https://api.coinbase.com/v2/prices/ETH-USD/spot');

out($curl->getResponseBody(), 1);

        

The shorthand method post() allows to send POST requests easily.


$curl = (new Curl())
    ->post('https://httpbin.org/post', array(
        'id' => '1',
        'content' => 'Hello world!',
        'date' => date('Y-m-d H:i:s'),
    )
);

out($curl->getResponseBody());
out($curl->getResponseHeaders());

        

The shorthand method put() allows to send PUT requests.


$curl = (new Curl())->put('https://httpbin.org/delay/5');
        
out($curl->getResponseBody());
out($curl->getResponseHeaders());

        

The shorthand method delete() allows to send DELETE requests.


$curl = (new Curl())->delete('https://httpbin.org/anything/old');
        
out($curl->getResponseBody());
out($curl->getResponseHeaders());

        

To send multi cURL request you will need to pass the word `multi` as an argument to Curl contructor and then chain requests.


$curl = (new Curl('multi'))
    ->addGet('https://httpbin.org/image/jpeg')
    ->addGet('https://httpbin.org/image/png')
    ->addPost('https://httpbin.org/delay/2')
    ->run();

out($curl->getResponseBody());

        
<< Prev Next >>