CURL is predefined php library which allow us to perform any web service action. It supports to connect any 3rd party application which is exposing services to outside world like Google Geo Distance, Yahoo Finanace API, Census API, etc,.. In Magento 2, CURL is organized as internal library and ensure to make secure curl request.
Main Class : [ Magento\Framework\HTTP\Client\Curl.php ]
You can include the curl class in your model / helper file via standard di method to perform a standard curl operation.
The Curl.php class file contains below list of important function which is part of any standard curl operation.
public function setHeaders($headers):
The function allows us to set array of header params for the curl operation and may contains valid credentials to make the call.
public function addHeaders($name, $value):
This function is responsible to add header param one by one in sequent way.
Ex : Adding content type header param in curl operation.
public function setCredentials($login, $pass):
Sometimes, the target system will allow us to consume the service after successful authentication process. This services are purely private access. The setCredentials() function is used to set the valid authentication credentials on curl object as part of header param.
public function get($uri):
This function is mainly used whenever we are passing the params as query string in the url & going to fetch the data from target system.
public function post($uri, $params):
This function is very useful whenever we are going to post the params to target system.
public function makeRequest($method, $uri, $params = []):
This function will support both GET / POST method in curl operation. Basically it accepts 3 main params.
$method get / post
$uri target url which we are going to connect
$params parameter which needs to be pushed to target system.
public function curlOption($name, $value ):
This function is more useful to set all curl options one by one like,
Ex :
$this->curl->curlOption(‘CURLRETURNTRANSFER’,’1’);
Below is standard PHP way,
public function curlOptions($arr):
It’s useful to set array of options in the same time.
I am seriously suggesting to use magento curl library to perform any curl related webservice calls which is safer compare than native php curl class.
Below is the reference code your quicker understanding.
Post By :Thamotharan