Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More โCreate reusable PHP cURL function for handling all HTTP methods including GET, POST, PUT, and DELETE requests to RESTful APIs. Learn to initialize cURL with curl_init, set custom headers, send data with different request methods, handle authentication, manage responses with curl_exec, and implement error handling. Complete examples for fetching data, creating resources, updating records, and deleting entries through API endpoints.
Interacting with APIs is a common task in PHP development. Whether you're fetching data or sending updates, this guide walks through handling GET, POST, PUT, and DELETE requests using a flexible function with cURL.
function callApiMethod($method, $url, $data = array()) {
$curl = curl_init($url);
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if (!$result) {
die("Connection Failure");
}
curl_close($curl);
return $result;
}
callApiMethod() acts as a universal function to perform API operations based on the method provided.curl_exec() function handles the actual request and returns the response.
// GET
$response = callApiMethod('GET', 'https://api.example.com/users/123');
var_dump($response);
// POST
$data = array('name' => 'John Doe', 'email' => 'john@example.com');
$response = callApiMethod('POST', 'https://api.example.com/users', $data);
var_dump($response);
// PUT
$data = array('email' => 'john.new@example.com');
$response = callApiMethod('PUT', 'https://api.example.com/users/123', $data);
var_dump($response);
// DELETE
$response = callApiMethod('DELETE', 'https://api.example.com/users/123');
var_dump($response);
This reusable PHP function simplifies how you interact with any RESTful API. By adjusting the HTTP method and parameters, you can manage data with ease. Want to explore more options? Visit the PHP cURL documentation. 
Search our archives or reach out to our team for solutions and expert advice.