There are many services that allow users shortened link such as bit.ly , adf.ly, goo.gl, ... In this article, I will guide you to use the google shortened link services to get short link from long link or reverse
Then, Get Public API Key Access
- GetShortURL from Long url
- GetLongURL from short url encode
You need define
Get API Key from Google Code
Go to http://code.google.com/apis/console/ create new account then enable URL Shortener APIThen, Get Public API Key Access
Class GooGl
Here I have written class Googl has 2 method:- GetShortURL from Long url
- GetLongURL from short url encode
You need define
$apiKey
(you get above) and $apiURL
(current, api url of googl is https://www.googleapis.com/urlshortener/v1/url)class GooGl
{
// get key from http://code.google.com/apis/console/
private $apiKey = '';
//API google shorten url
private $apiURL = 'https://www.googleapis.com/urlshortener/v1/url';
private $url;
/**
* check curl_init off & trigger error
*/
public function __construct()
{
if (!function_exists('curl_init')) {
trigger_error('cURL off');
}
$this->apiURL = $this->apiURL . '?key=' . $this->apiKey;
}
public function setURL($url)
{
$this->url = $url;
return $this;
}
public function getShortURL()
{
$jsonResponse = $this->curlRequest($this->apiURL, json_encode(array('longUrl' => $this->url)));
return $jsonResponse->id;
}
public function getLongURL()
{
$jsonResponse = $this->curlRequest($this->apiURL . '&shortUrl=' . $this->url);
return $jsonResponse->longUrl;
}
/**
* if $jsonData is null => getLongURL, method GET
* else getShortURL, method POST
*/
private function curlRequest($apiURL, $jsonData = null)
{
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, $apiURL);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
if ($jsonData !== null) {
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
}
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curlObj);
curl_close($curlObj);
return json_decode($response);
}
}
You can download full source code here: Download
Usage
You can setURL then get direct:$gooGl = new GooGl();
echo $gooGl->setURL('')->getShortURL();
//
echo $gooGl->setURL('')->getLongURL();
or
$gooGl = new GooGl();
$gooGl->setURL($url);
if ($type == 'short') {
echo $gooGl->getShortURL();
} else {
echo $gooGl->getLongURL();
}