How To

How to Call API in PHP Using Curl

In this article we are going to learn how to call an API in PHP file using cURL method. PHP provides effortless inbuilt method cURL to call API and process its response.

What is cURL in PHP?

cURL is the method to request web URLs or APIs in PHP. It helps to get data from other sources or websites rather than the only database.

Must Read: How to Create a Simple PHP REST API

How To Use cURL To Call APIs in PHP?

cURL is an effortless method in PHP to call an API. We have to use the curl function with some parameters to call an API.

Example

This example explains the simplest way to call an API using cURL in PHP.

<?php
header("Access-Control-Allow-Origin: *"); # enable Cross Origin [CORS]
$url = 'http://dummy.restapiexample.com/api/v1/employees'; # API Link

$ch = curl_init(); # initialize curl object
curl_setopt($ch, CURLOPT_URL, $url); # set url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); # receive server response
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); # do not verify SSL

$data = curl_exec($ch); # execute curl
$httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); # http response status code
curl_close($ch); # close curl

echo "Errors: ".curl_error($ch)."<br>"; # Print errors if any
echo "Status: ".$httpstatus."<br>"; # Print Response Status Code
var_dump($data); # Print Response Data
?>

Read Also: PHP Object to JSON Object [Encode & Decode]

Conclusion

I hope now you have a complete understanding of cURL and request of APIs in PHP. There are lots of other features of cURL which are useful to manage headers, data and responses of the request.

Keep exploring, Enjoy Coding 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

4 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago