Latest News

Short URL Google dengan API


Kebetulan lagi oprek2 seputar short URL nih, jadi biar engga lupa boleh yah saya simpan di mari, siapa tau ada yang lagi oprek API short URL juga.

Berikut langkah-langkahnya mas bro:

Buat sebuah class:
class GoogleUrlApi {

 // Constructor
 function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
  // Keep the API Url
  $this->apiURL = $apiURL.'?key='.$key;
 }

 // Shorten a URL
 function shorten($url) {
  // Send information along
  $response = $this->send($url);
  // Return the result
  return isset($response['id']) ? $response['id'] : false;
 }

 // Expand a URL
 function expand($url) {
  // Send information along
  $response = $this->send($url,false);
  // Return the result
  return isset($response['longUrl']) ? $response['longUrl'] : false;
 }

 // Send information to Google
 function send($url,$shorten = true) {
  // Create cURL
  $ch = curl_init();
  // If we're shortening a URL...
  if($shorten) {
   curl_setopt($ch,CURLOPT_URL,$this->apiURL);
   curl_setopt($ch,CURLOPT_POST,1);
   curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
   curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
  }
  else {
   curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
  }
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  // Execute the post
  $result = curl_exec($ch);
  // Close the connection
  curl_close($ch);
  // Return the result
  return json_decode($result,true);
 }
}

lalu lanjutkan dengan perintah untuk menampilkan ke program kita, jangan lupa siapkan APIKey google short URl nya bias di dapatkan disini https://code.google.com/apis/console/

$key = 'xhjkhzkhfuh38934hfsdajkjaf';
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten("http://linkyangmaudishort");
echo $shortDWName; // hasil output


0 Response to "Short URL Google dengan API"