Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Created February 11, 2024 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyazincahya/17e6de230b56026f690450eaaa2a73eb to your computer and use it in GitHub Desktop.
Save dyazincahya/17e6de230b56026f690450eaaa2a73eb to your computer and use it in GitHub Desktop.
Simple Helper file_get_contents PHP for access API with method GET POST PUT and DELETE
<?php
function makeApiRequest($url, $params = [], $method = 'GET') {
$options = [
'http' => [
'method' => $method,
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($params),
],
];
// If it's a GET request, append parameters to the URL
if ($method === 'GET' && !empty($params)) {
$url .= '?' . http_build_query($params);
}
// Create a stream context with the specified options
$context = stream_context_create($options);
// Make the request using file_get_contents with the created context
$response = file_get_contents($url, false, $context);
// Return the API response
return $response;
}
?>
@dyazincahya
Copy link
Author

how to usage?

<?php 

  // Example usage for GET request
  $name = 'kim';
  $countryId = 'US';
  $api_url_get = 'https://api.example.io';
  $params_get = [
      'name' => $name,
      'country_id' => $countryId,
  ];

  $responseGet = makeApiRequest($api_url_get, $params_get, 'GET');
  echo "GET Response: $responseGet\n";


  // Example usage for POST request
  $api_url_post = 'https://api.example.com/posts';
  $params_post = [
      'title' => 'New Post',
      'content' => 'This is the content of the new post.',
  ];

  $responsePost = makeApiRequest($api_url_post, $params_post, 'POST');
  echo "POST Response: $responsePost\n";


  // Example usage for PUT request
  $api_url_put = 'https://api.example.com/123';
  $params_put = [
      'title' => 'Updated Post',
      'content' => 'This is the updated content of the post.',
  ];

  $responsePut = makeApiRequest($api_url_put, $params_put, 'PUT');
  echo "PUT Response: $responsePut\n";


  // Example usage for DELETE request
  $api_url_delete = 'https://api.example.com/123';
  $responseDelete = makeApiRequest($api_url_delete, [], 'DELETE');
  echo "DELETE Response: $responseDelete\n";

?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment