In PHP development, it is common to interact with third-party services or other systems via data exchange. APIs are one of the most frequently used methods. Using PHP's built-in cURL extension, you can conveniently send HTTP requests to communicate with APIs. This article demonstrates a complete example of how to use PHP cURL to operate API interfaces.
Before starting, ensure the cURL extension is installed in your PHP environment. You can check this via the command line:
php -i | grep -i curl
If the output contains information related to curl, the extension is installed. Otherwise, you can install it using the following command (for Debian/Ubuntu):
sudo apt-get install php-curl
For better code organization and maintainability, we encapsulate cURL requests into a class.
class CurlApiClient { private $baseUrl; public function __construct($baseUrl) { $this->baseUrl = $baseUrl; } public function request($endpoint, $params = array(), $method = 'GET') { $url = $this->baseUrl . '/' . $endpoint; $ch = curl_init(); if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); } else { $url .= '?' . http_build_query($params); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new Exception("cURL request error: " . $error); } curl_close($ch); return $response; } }
Here is an example of how to use the class above to make API requests:
$baseUrl = 'https://api.example.com'; $apiKey = 'your-api-key'; $client = new CurlApiClient($baseUrl); try { $endpoint = 'users'; $params = array('apiKey' => $apiKey); $response = $client->request($endpoint, $params, 'GET'); echo $response; } catch (Exception $e) { echo 'Request failed: ' . $e->getMessage(); }
The code above demonstrates a GET request. To make a POST request, just change the last parameter to "POST" and pass the relevant parameters accordingly.
This article introduced how to install the cURL extension in PHP, encapsulated a reusable API client class, and showed practical examples of sending GET and POST requests. This approach helps modularize API calls and makes integration easier to maintain, suitable for various PHP projects.