Skip to content

Instantly share code, notes, and snippets.

@sophy
Created February 27, 2011 15:49
Show Gist options
  • Save sophy/846274 to your computer and use it in GitHub Desktop.
Save sophy/846274 to your computer and use it in GitHub Desktop.
<?php
/**
* Define google url shortener api
*/
define("API_URL", "https://www.googleapis.com/urlshortener/v1/url?key=");
class GoogleURL
{
/**
*
* @var string
*/
private $_apiUrl;
/**
*
* @var string
*/
private $_shortUrl;
public function __construct($apiKey) {
//Google URL Shortener
$this->_apiUrl = API_URL.$apiKey;
}
public function shorten($longUrl)
{
$data = $this->getContent($longUrl);
$this->_shortUrl = $data->id;
return $data->id;
}
public function expand($shortUrl)
{
$data = $this->getContent($shortUrl, "expand");
$this->_shortUrl = $data->id;
return $data->longUrl;
}
public function getLongUrlCliks(){
$data = $this->getContent($this->_shortUrl, 'info');
return $data->analytics->allTime->longUrlClicks;
}
public function getShortUrlClicks(){
$data = $this->getContent($this->_shortUrl, 'info');
return $data->analytics->allTime->shortUrlClicks;
}
private function getContent( $url, $requestType = "shorten" ){
$curl = curl_init();
if( $requestType === "expand" ){
curl_setopt($curl, CURLOPT_URL, $this->_apiUrl.'&shortUrl='.$url);
}else if( $requestType === "info" ){
curl_setopt($curl, CURLOPT_URL, $this->_apiUrl.'&shortUrl='.$url.'&projection=FULL');
}else{
curl_setopt($curl, CURLOPT_URL, $this->_apiUrl);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array('longUrl' => $url)));
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
//change the response json string to object
return json_decode($response);
}
}
// Example
$url = new GoogleURL('your_google_shortener_api_key');
echo $url->expand($url->shorten("http://www.google.com/")),'<br/>';
echo $url->getLongUrlCliks(), "<br/>";
echo $url->getShortUrlClicks(), "<br/>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment