Sharing a short URL instead of long Url is amazing. First of all they dont have to write to much to acess your url and no one knows what it is all about until they will not open it. In this tutorial i will show you how you can create short url using Google URL Shortner API in PHP. We will use CURL to make it working.
First we will create a class with a url shortner function
class urlShortnerClasss{ public function createShortURl($longurl){ } }
Above is the structure of our class and we will update our createShortURL function.
function createShortURl($longurl){ $key="Enter Your Google Key"; $url = "https://www.googleapis.com/urlshortener/v1/url?key=$key"; $data=array("longUrl" => $longurl); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json")); $response = curl_exec($ch); $myarray= json_decode($response); $newarray=array("shortUrl"=>"$myarray->id","Mainurl"=>"$myarray->longUrl"); return $newarray; }
As you can see we have used the Google API to create the ShortURL using CURL. You have to obtain the Key from Google and than we will create the data array and pass the values to the API URL after Json Encoding.
In return we will decode the received result and create an array of short url and long url. For getting the shorturl we will use the array ($newarray) which is having 2 values.
For using it we will create the object of the call and use the createShortURl function. ex –
$shortClass=new urlShortnerClasss(); $details=shortClass->createShortURl("www.vivekmoyal.in"); print_r($details);
Hope you like our tutorial if you have any issue than please let me know i will surely help you.
No Comments