In communicating with other resources, several components are needed to fulfill this, one of which is cURL. cURL will assist developers in communicating with other websites via HTTP, FTP and TELNET protocols. cURL is already available in other programming language libraries such as Python or Ruby. With this method, websites can do many things, various advanced features can retrieve or send data through just a few command lines.
1. What is cURL in PHP
cURL stands for client URL which was formerly HttpGet, cURL is a special library that is used to send or receive data from other resources using URLs.
This library can be run in the command line or in the script line and is usually used to interact with web services or APIs to retrieve the required data. Understanding cURL is very important if you are working on a web services or API project.
And also this library is highly recommended for websites that are quite complex in interacting with other resources compared to using the file_get_contents function.
Although the use of cURL is quite verbose in every line of code, this library is actually much better than the use of PHP's built-in data retrieval such as file_get_contents, see the sample code in file_get_contents below:
$content = file_get_contents("https://www.example.com");
It can be seen that the drawback of the file_get_contents function is that it cannot handle errors and has no other options, such as using cookies, proxies, adding other required information, user agents and authentication.
In addition to sending and receiving data, this library can do many things, such as logging in to Facebook, and can even change the status on Facebook with just cURL. Next, it can do web scraping, form submissions, delete data, save data, retrieve data, upload files and upload files. many more. cURL is a great library for doing a lot of things with various options from URL requests.
2. Get to know the basic structure of cURL
There are some basic structures that you need to understand including initialization, option set, execution, handle and closing execution, see the syntax below:
<?php
$url = 'https://www.example.com';
// initialization
$ch = curl_init();
// set option set
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// execute
$output = curl_exec($ch);
// close execution on cURL
curl_close($ch);
echo $output;
Not only that, this library can add handling or error checking if something unexpected happens, some additional scripts see the script below:
<?php
$url = 'https://www.example.com';
// initialization
$ch = curl_init();
// set option set
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// execute
$output = curl_exec($ch);
// error handling
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
// close execution on cURL
curl_close($ch);
echo $output;
It should be understood that in order to handle syntax errors, we need to use $output === false for comparison, not like this $output == false, because we need to distinguish between values that contain empty and values that contain booleans.
For each explanation of the basic structure of cURL, here is a brief explanation:
Initialization
Initialization indicating the function will be executed.
Option set
The option set aims to assign a value to each option to get or receive what we want to get, such as which URL to go to, whether to use a proxy, whether to change other methods such as POST, PUT or DELETE, whether to require information from the header and so forth.
Execution
This function will return the result we have defined in each option.
Handle error
Handles errors in cURL, then provides information to developers about errors that occur.
And what's great, this library can provide a variety of information from the destination URL in just one line of code.
curl_getinfo($ch);
It can be used for various needs and get additional information. Later the output value of curl_getinfo() will be returned as an array, here is some additional information in cURL:
- http_code
- header_size
- total_time
- size_download
- speed_download
- ssl_verify_result
- content_type
- and many more
For example, we will want to get data from the API we are going to, but we also want to get information about the status code at the URL, to activate this feature, you can see the code below:
<?php
$url = 'https://api.example.com/api/users?output=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$status_code = $info['http_code'];
$results = json_decode($output);
if($status_code == '200') {
print_r($results);
}
3. Using the POST method with cURL
In some HTML forms, usually the website owner has set the form using the POST method, this method aims to send data via HTTP Request. Apart from that, we can also use cURL to send some data without having to fill in the HTML form that has been provided.
This method will send data via the POST option specified by the developer to a specific URL (server) for processing, you can see the sample code below:
<?php
$url = "https://api.example.com/api/users/registration";
$post_data = array (
'username' => 'test',
'password' => 'pass',
'email' => '[email protected]',
'action' => 'Submit'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
if($result->status) {
echo 'data added successfully';
} else {
echo 'data failed to add';
}
4. Using the GET method with cURL
To perform the GET method, we can only send data with a URL in the form of a query. It's actually simple, for example, if you want to display the results of a particular query in Google, you can try it with the following code:
<?php
$url = 'https://www.google.com/search?q=somequeries';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
curl_close($curl);
echo $data;
If the allow_url_fopen feature is not enabled, alternatively using cURL is the right option.
5. Using the PUT method with cURL
In using the PUT method, it is actually almost the same as the POST method, but the difference is in the set of options used. It aims to determine what type of method is used and automatically eliminate other methods such as POST, see the code sample below:
<?php
$url = "https://api.example.com/api/users/2";
$data = array(
'name' => 'test1234',
'email' => '[email protected]'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
if($result->status) {
echo 'data updated successfully';
} else {
echo 'data failed to update';
}
This PUT method is usually used to update data in a RESTful API, server or other.
6. Using the DELETE method with cURL
To use this method, not much different from other methods such as POST or PUT, only change the set of options on the type of value to be determined. See the code example below:
<?php
$url = "https://api.example.com/api/users/2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
if($result->status) {
echo 'data deleted successfully';
} else {
echo 'data failed to delete';
}
This method can be used on a RESTful API or server to quickly delete the selected data.
7. Fetch data from API with cURL
This method is often used to retrieve data through the API in the form of JSON output, which will later be converted into an array for reprocessing. To run this perfectly, an additional function is needed, namely json_decode which functions to convert data from JSON into an array, see the example syntax below:
<?php
$url = 'https://api.example.com/api/users?output=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$jsonData = curl_exec($ch);
curl_close($ch);
$result = json_decode($jsonData);
print_r($result);
Using this method is very commonly used by developers in communicating with APIs or web services that are faster and more perfect by using cURL.
8. Multi cURL feature
Multi cURL is another interesting and powerful feature of this library. This feature can connect to multiple URLs simultaneously and async, and will execute the related URLs sequentially, so that the next request will be delayed before the first request has finished its execution.
As an example of this multi cURL, we take an example from the official PHP site:
<?php
$ch_1 = curl_init('https://webservice.one.com/');
$ch_2 = curl_init('https://webservice.two.com/');
curl_setopt($ch_1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, true);
$mh = curl_multi_init();
curl_multi_add_handle($mh, $ch_1);
curl_multi_add_handle($mh, $ch_2);
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
$response_1 = curl_multi_getcontent($ch_1);
$response_2 = curl_multi_getcontent($ch_2);
echo "$response_1 $response_2";
This feature is perfect for executing code simultaneously without having to regenerate code for different URLs.
Conclusion
By using this library in PHP, of course it will speed up the data processing process in your website application, cURL can also be used in many things such as payment gateway services, APIs, scraping, adding data, deleting data and so on.