
In this post, I’ll show you a cURL example in PHP. Basically, cURL is a library that allows you to make HTTP requests in PHP. In other words, we can say cURL is a way to request a URL from PHP code to get a response from it. It will supports both GET and POST methods requests.
cURL provides an easy way to communicate with other different remote sites. It is a very useful technique which can be used by everyone for requesting to remote websites.
Contents
How cURL will work in PHP
Here we can explain how cURL works in PHP and what is the process for the request to remote sites. The following methods are used for cURL request:
- Initialization of cURL session
$ch = curl_init();
- Setting the options for a cURL. cURL have too many options.These are some important options are given below.
curl_setopt($ch, CURLOPT_URL, $url); //The URL to request.
curl_setopt($ch, CURLOPT_POST, true); //It will used to HTTP POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //The data which will you want to POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Return the response data from requested URL
- Execution of cURL session
$output = curl_exec($ch);
- Return the last error
curl_errno($ch);
- Return the error message.
curl_error($ch);
- Closing the cURL session
curl_close($ch);
cURL request methods
There are bascically two methods in cURL for requesting the data to domains.
- POST request
- GET request
cURL example in PHP by POST request
The following complete code snippets for the cURL request with data using the POST method.
$url = "http://www.examplesite.com/api/getuserdetails.php";
$arraydata = array(
"email" => '[email protected]'
);
$data = json_encode(arraydata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error Message:' . curl_error($ch);
}
curl_close($ch);
cURL example in PHP by GET request
The following complete code snippets for the cURL request with data using the GET method.
$email = "[email protected]";
$url = "http://www.examplesite.com/api/getuserdetails.php?email=".$email;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, GET);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error Message:' . curl_error($ch);
}
curl_close($ch);
Output
{
"userdetails": [
{
"cid": "123",
"cname": "Test User"
}
]
}
Did you find this page helpful?
X