-
-
Save mach3/69e4a0c19e4776924a21 to your computer and use it in GitHub Desktop.
Shorten and expand urls using Google URL Shortener API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class GoogleUrl { | |
const EMPTY_KEY = "Empty Key"; | |
const EMPTY_URL = "Empty URL"; | |
private $rest = "https://www.googleapis.com/urlshortener/v1/url"; | |
private $key = null; | |
public function __construct( $key = null ){ | |
$this->setKey( $key ); | |
} | |
public static function create( $key = null ){ | |
$ins = new self(); | |
$ins->setKey( $key ); | |
return $ins; | |
} | |
public function setKey( $key ){ | |
$this->key = $key; | |
} | |
public function shorten( $url ){ | |
if( empty( $this->key ) ){ throw new Exception( self::EMPTY_KEY ); } | |
if( empty( $url ) ){ throw new Exception( self::EMPTY_URL ); } | |
$curl = curl_init(); | |
curl_setopt_array( $curl, array( | |
CURLOPT_URL => "{$this->rest}?" . | |
http_build_query( array( "key" => $this->key ) ), | |
CURLOPT_HTTPHEADER => array("Content-Type: application/json" ), | |
CURLOPT_POST => true, | |
CURLOPT_POSTFIELDS => json_encode( array( "longUrl" => $url ) ), | |
CURLOPT_RETURNTRANSFER => true | |
)); | |
$res = curl_exec( $curl ); | |
curl_close( $curl ); | |
return json_decode($res); | |
} | |
public function expand( $url ){ | |
if( empty( $this->key ) ){ throw new Exception( self::EMPTY_KEY ); } | |
if( empty( $url ) ){ throw new Exception( self::EMPTY_URL ); } | |
$curl = curl_init(); | |
curl_setopt_array( $curl, array( | |
CURLOPT_URL => "{$this->rest}?" . | |
http_build_query( | |
array( "key" => $this->key, "shortUrl" => $url) | |
), | |
CURLOPT_RETURNTRANSFER => true | |
)); | |
$res = curl_exec( $curl ); | |
curl_close($curl); | |
return json_decode( $res ); | |
} | |
} | |
// test | |
$gu = GoogleUrl::create( "[your-api-key]" ); | |
try { | |
// shorten url | |
$shorten = $gu->shorten( "http://www.mach3.jp" ); | |
var_dump( $shorten ); | |
// expand the shorten | |
$expand = $gu->expand( $shorten->id ); | |
var_dump( $expand ); | |
} catch( Exception $e ){ | |
die( $e->getMessage() ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment