cURL – Client URL library is used to communicate with different types of servers with protocols FTP, HTTP, telnet, gopher and more.
In PHP, we have to install the libcurl library for working with the cURL script. If your PHP setup is not enabled with the cURL library, find the steps to enable this library in the PHP cURL post article.
If we used any one of the AMP bundles like XAMPP, to create a PHP environment, then the cURL library will come up with this bundle.
After cURL installation, we should enable this extension in the PHP configuration file.
//Remove semi colon (;) to enable
;extension=php_curl.dll
For handling remote file access, the cURL as an intermediary is used for,
Without cURL, we can read file contents in PHP using file_get_contents() function. For example, file_get_contents() can read remote data via URL.
It requires the allow_url_fopen configuration directive must be set. But is not advisable because of security reasons.
In a PHP program, the cURL portion should be enclosed within these two pairs of functions.
$ch = curl_init(URL Syntax);
curl_close($ch);
The curl_init() function returns the cURL session handle with respect to the given file URL. And then, the curl_close() function will be an end delimiter to close the cURL session with respect to its handle.
PHP curl_setopt() function is used to set options. It receives the cURL handle, option’s name and value as its parameters.
We can use another cURL function curl_setopt_array() to set an array of multiple options at a push.
curl_setopt ($ch, CURLOPT_HEADER, 1);
Like PHP, the GET and POST methods are used for sending cURL requests where GET is the default. The CURLOPT_POST constant is used for sending a POST request. And the parameter CURLOPT_POSTFIELDS is for sending the parameter array of the field: value pairs.
After setting request methods and parameters, the curl_exec() function is used for executing the cURL request.
$result = curl_exec($ch);
This function returns either boolean values or string data based on the value of option CURLOPT_RETURNTRANSFER.
This PHP example is to get the body content from the given remote URL.
<?php
$url = "http://php.net/";
$content = curlRequest($url);
print $content;
function curlRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
?>