Skip to content

Instantly share code, notes, and snippets.

@saundersalex
Created December 20, 2011 18:49
Show Gist options
  • Save saundersalex/1502719 to your computer and use it in GitHub Desktop.
Save saundersalex/1502719 to your computer and use it in GitHub Desktop.
Bitly API Class
<?php
/*
* ----------------------
* bitly.class.php
* ----------------------
*
* Bitly class used for calling all the different API functions provided by the Bitly API.
*
* Author: Alex Saunders
* Email: [email protected]
* Date Created: December 19, 2011
* Date Updated: December 19, 2011
* Version: 1.0
*
*/
class Bitly {
// Bitly Username
private $username = 'YOUR_BITLY_USERNAME';
// Bitly API Key
private $apiKey = 'YOUR_API_KEY';
// Bitly API URL
private $api = 'http://api.bitly.com/v3/';
// Nullary Constructor
public function __construct() { }
/**
* Create an API request of the given service with the paramaters provided.
* @param String $service The name of the API service you would like to call.
* @param String $params The paramaters the service depends on.
*/
public function request( $service, $params ) {
// Begin constructing the request URL out of the service & login credentials.
$request = $this->api . $service . '?login=' . $this->username . '&apiKey=' . $this->apiKey;
// Go through the paramaters array, and add the key/value pair to the request.
foreach( $params as $key => $value ) {
$request .= '&' . $key . '=' . $value;
}
// Blast the request to curl_get and return the response.
// curl_get returns an associative array from the json response the Bitly API returns.
// So this function will return said associative array.
return $this->curl_get( $request );
}
/**
* CURL to the Bitly API.
* @param String $url The URL to query the Bitly API with.
*/
private function curl_get( $url ) {
// Initialize the curl session.
$curl = curl_init();
// Set Curl Options
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10
);
// Set curl options
curl_setopt_array( $curl, $options );
// Execute the curl request.
$response = curl_exec( $curl );
// Close curl session.
curl_close( $curl );
// Return the CURL response.
// Bitly returns JSON or XML. JSON By default.
// Decoding the response is up to the user of the class.
return $response;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment