Curl is another php http
request tool for sending http
requests, be it GET, POST, PUT
etc. It is also used to integrate with web services.
You may want to search for my other shot here on Edpresso on How to use Guzzle Http client request in Laravel.
You don’t need to run a composer command to use Curl
, as it comes pre-installed in your PHP
server.
Let’s look at how to make a get
request.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://example.com",// your preferred link
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
// Set Here Your Requesred Headers
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
The code above is self-explanatory, as it is readable on its own.
We send a get
request to the example.com
url
and set a timeout for this request.
From the code, we also specify the content type, which is application/ json
.
In the final stage, we send the request using the curl_exec()
method.
We also store any possible errors using the curl_error()
method.
Lastly, we add an if
statement to check that there are no errors in the run.
Let’s see how to send a request for the post
method.
$data1 = [
'data1' => 'value_1',
'data2' => 'value_2',
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://example.com",// your preferred url
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data2),
CURLOPT_HTTPHEADER => array(
// Set here requred headers
"accept: */*",
"accept-language: en-US,en;q=0.8",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
Though similar to the get
request, the post
request has some slight differences, like the CURLOPT_MAXREDIRS
. This limits the number of redirects and the $data1
variable, which is the data value we are sending.
Note that we are using example.com, which is just for illustration. In this shot we just use
print_r(json_decode($response))
, but you will want to work with the response or save it to your database.