Last active
February 11, 2024 08:21
-
-
Save dyazincahya/dc6c947a984794db35e45f0a2aed35ea to your computer and use it in GitHub Desktop.
Simple Helper cURL PHP for access API with method GET POST PUT and DELETE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function makeApiRequest($url, $params = [], $method = 'GET') { | |
// Initialize cURL session | |
$ch = curl_init($url); | |
// Set common cURL options | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string instead of outputting it | |
// Set method-specific cURL options | |
if ($method === 'POST') { | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); | |
} elseif ($method === 'PUT') { | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); | |
} elseif ($method === 'DELETE') { | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); | |
} elseif ($method === 'GET') { | |
// Append parameters to the URL for GET requests | |
if (!empty($params)) { | |
$url .= '?' . http_build_query($params); | |
} | |
} | |
// Execute cURL session and get the response | |
$response = curl_exec($ch); | |
// Check for cURL errors | |
if (curl_errno($ch)) { | |
echo 'Curl error: ' . curl_error($ch); | |
} | |
// Close cURL session | |
curl_close($ch); | |
// Return the API response | |
return $response; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to usage?