Bladephp: Now with 8+ codeigniter, php, and laravel project 8+ php project From $37/Month From Rs. 2499/Month

How to generate short url using PHP and Google API

by
Category:php
php
How to generate short url using PHP and Google API

Google has had a URL shortening domain for quite a while now but it wasn't until recently that Google exposed the URL shortening API to the public. I took a few minutes to review their API and created a very basic GoogleUrlApi class that will shorten long URLs and expand shortened URLs. You may also like How to Login with Google Account in CodeIgniter and Pick up Location and Drop Location line draw in google map API using javascript.

HTML Code

<html>
<body>
    <form method="post" action="">
        <input type="text" name="url_val">
        <input type="submit" name="submit_url">
    </form>
</body>
</html>

PHP Code

<?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);
    $json = json_decode($response);

    curl_close($curlObj);

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

0 Comments


Html code work in comment box


Related Post