Skip to content

Instantly share code, notes, and snippets.

@iprodev
Created December 14, 2018 18:46
Show Gist options
  • Save iprodev/8cebcb80e50569710c64befc92f5d75d to your computer and use it in GitHub Desktop.
Save iprodev/8cebcb80e50569710c64befc92f5d75d to your computer and use it in GitHub Desktop.
PHP : Make API Calls in PHP
<?php
/**
* Make API Calls in PHP
*
* @param string $method The HTTP method (GET or POST) to be used
* @param string $url The URL
* @param array $data The data should send with POST
* @return string Response from the url
*/
function CallAPI( $method, $url, $data = false ) {
$curl = curl_init();
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_PUT, 1 );
break;
default:
if ( $data )
$url = sprintf( "%s?%s", $url, http_build_query( $data ) );
}
// Optional Authentication:
curl_setopt( $curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $curl, CURLOPT_USERPWD, "username:password" );
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $curl );
curl_close( $curl );
return $result;
}
// Get request
$get_response = CallAPI( 'GET', 'http://example.com' );
echo $get_response;
// Post request
$data = array();
$data['name'] = 'joashp';
$data['email'] = '[email protected]';
$post_response = CallAPI( 'POST', 'http://example.com', $data );
echo $post_response;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment