All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Generate Short URLs Using PHP And Google API

Last Updated : Jul 1, 2023

IN - PHP Google API HTML | Written & Updated By - Amruta

In this tutorial we will show you how to generate short URL using PHP and Google API, Google has tons of API to make hard and complex things easy and one of them is Google URL Shortner service there is an API to generate shorted URL from long URL by passing URL value in API.

You may also like create short URL using PHP only.

Generate Short URLs Using PHP And Google API

To Generate Short URL It Takes Only Two Steps:-

  1. Make a HTML file to send URL
  2. Make a PHP file to generate Short URL

Step 1. Make a HTML file to send URL

We make a HTML file and save it with a name short_url.html

<html>
<body>
<div id="wrapper">
<form method="post" action="create_url.php">
 <input type="text" name="url_val">
 <input type="submit" name="submit_url">
</form>
</div>
</body>
</html>

In this step we create a form to send url to 'create_url.php' to create shorter version of that url. You may also like detect url in input using jQuery.

Step 2. Make a PHP file to generate Short URL

We make a PHP file and save it with a name create_url.php

<?php
if(isset($_POST['submit_url']))
{
 $long_url=$_POST['url_val'];
 $apiKey = 'Your API Key';

 $data = array('longUrl' => $long_Url, 'key' => $apiKey);
 $jsonData = json_encode($data);

 $curlObj = curl_init();

 curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
 curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
 curl_setopt($curlObj, CURLOPT_HEADER, 0);
 curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
 curl_setopt($curlObj, CURLOPT_POST, 1);
 curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

 $response = curl_exec($curlObj);

 // Change the response json string to object
 $json = json_decode($response);

 curl_close($curlObj);

 echo 'Your Short URL is: '.$json->id;
}
?>

In this step we get the url value and then insert API key read our login with google using PHP to know how to get your Google API Key then we put all the data in array and use json_encode before send the data to google api then we use google url shortner predefined function to get the shorted url and then display that shorted url.

You can also view our check url existence using PHP tutorial with this code to check if url is valid or not.

That's all, this is how to generate short URLs using PHP and Google API. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on create your own url shortener php helps you and the steps and method mentioned above are easy to follow and implement.