cURL is a very powerfull system which allows us to transfer data across a wide variety of protocols. cURL is commonly used to send data across websites which includes API interaction. Using a cURL request, we can do the basic HTTP request, the more complex FTP upload or interaction with an authentication enclosed HTTPS site. In this section we will go through how cURL is intialized, how to send cURL request and close the requests.
Before sending a cURL request, we need to initalize the cURL first. This can be done by the cURL function curl_init().This function returns a cURL resource. There is only one parameter to the this function, which is the URL(request we want to send to). Below is the example to initialize a cURL request.
$curl = curl_init('http://cURL.com');
We can also initialize cURL request by another setting method:
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://cURL.com');
curl_setopt() method contains three parameters i,e the cURL resource, the setting and the value. There are several setting method avaialable in cURL.
After initializing the request, we need to send the cURL request. For that cURL defines a method called curl_exec() which will execute the cURL request. This return values for this function can be:
- false - if there is an error executing the request
- true - if the request executed without error and CURLOPT_RETURNTRANSFER is set to false
- The result - if the request executed without error and CURLOPT_RETURNTRANSFER is set to true
Note : CURLOPT_RETURNTRANSFER - Returns the response as a string instead of outputting it to the screen
Using the previous example, if we want to get the result as the return value, we could use the following function:
$result = curl_exec($curl);
Here the $result contains the response from the page - which might be a string or a full site's HTML.
Finally you have to close the cURL request so that you can free up some system resources. For this, you could use curl_close() method which takes the resource as its parameter.
Hope this Helps..