cURL stands for client URL which can also be written as curl.
curl is a command line tool to transfer data to and from a server. curl is also used to get/send information using APIs.
let’s have a look into that.
Instead of using default PHP curl we can use Magento’s class Magento\Framework\HTTP\Client\Curl to work with HTTP protocol using Curl library.In other words Magento made it easy to use curl by implementing Curl class methods.
First, let’s create an instance of Magento\Framework\HTTP\Client\Curl.
Instance of curl will be created by above code which is then used to access methods of Magento\Framework\HTTP\Client\Curl class
// get method
By using the Instance we created Earlier $this->curl we will call get method
// post method
Additionally We can also set headers, basic authorization, additional curl options and cookies in the cURL request.
we have to add these methods before GET or POST method.
We will learn in detail how to set headers, basic authorization, additional curl options, and cookies in curl request
These two methods are used to set the curl headers :
Both addHeader() and setHeader() will add a header and value to the response. The difference between set and add shows up when the header is there.
addHeader() adds an additional value, whereas setHeader() overwrites the existing value.
addHeader() accepts two parameters. First parameter is header name and second is the header value.
setHeader() accepts an array as a parameter.
Set the basic authorization using setCredentials().
It is equivalent to setting CURLOPT_HTTPHEADER value:
"Authorization : "."Basic ".base64_encode($userName.":".$password)
The setOption() accepts two parameters. The cURL option name and the cURL option value.
The setOptions() accepts Single parameter as an array.
These two methods are used to set the curl cookies :
The addCookie() accepts two parameters. First parameter is cookie name and second parameter is cookie value.
The setCookies() accepts one parameters as an array.
We hope above guideline helps you to clearly understand How to Use curl in Magento 2. One can use deafault curl class for API Call and also instead of using default PHP curl one can use Magento’s class. We hope you have learned something useful from this MageAnts article. In case of any kind of problem with the above code implementation, you can contact us or let us know in comment section.