cURL stands for client URL. This is basically a library which allows communicating with many different type of server with different protocols like HTTP, FTP etc.
When we work on XAMPP or WAMP(localhost) then cURL library is included in it.
To enable the cURL we have to edit php.ini file which are shown below. Instead of cURL , there is a PHP function like file_get_contents() which is also used to get remote content.
Steps to Enable cURL
Open php.ini file Find ;extension=php_curl.dll Remove semi-colon(;) to activate cURL.
Some operations which can be performed using cURL which are as follows:• File upload and download from remote server.
• Download HTML with URL in PHP.
• Authentication process (Login to other website with permissions)
Basic cURL functions
1. curl_init – It is used to initialize new session. It returns cURL handle which is passed to other curl function.
$curl = curl_init(); //initialise
2. curl_setopt – It is used set option what we want to do with cURL library. We put cURL handle within it.
curl_setopt ($curl, CURLOPT_HEADER, 1);
3. curl_exec – Used to execute cURL session . It return true if it is success else return false.
$output = curl_exec($curl);
4. curl_close – used to close the current cURL session.
curl_close($curl);
How Does the cURL Work?
Let’s see the basic steps of a cURL request in PHP. There are four main steps:
Initialize a cURL session
Set the options
Execute and Fetch Result
Close a cURL session
Example of cURL.
<?php // 1. Initialize a cURL session $ch = curl_init(); // 2. Set the options, including the url curl_setopt($ch, CURLOPT_URL, "https://www.vikashkumarsingh.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 3. Execute and fetch the resulting output $output = curl_exec($ch); // 4. Close a cURL session curl_close($ch); ?>
Here in above example you have seen CURLOPT_HEADER is set to 0 to exclude header info from response from output.
CURLOPT_RETURNTRANSFER set to 1 to return the results instead of outputting it.
For downloading remote contents as file we have cURL option like CURLOPT_FILE which open or create a file to store cURL output. It will write cURL result to a file.
If we want to get remote content from client URL then we just pass URL within curl_init(“URL”) and we will get remote content as a response.