Create TinyURL Using Bitly API in PHP

Are you looking to create short links for the long URLs? Short links or TinyURL are easy to share on email and on social media. In this article, we study how to create a short link using the Bitly API and PHP.

Bitly is a URL shortener and link management platform. They allow us to create short links and track the individual link analytics.

Popular websites like YouTube, Facebook, Twitter provide a short version of a long URL. When we run the short URL on the browser, it will redirect automatically to the main URL.

That being said, let’s see how to create short links using Bitly API in PHP.

Getting Started

To get started, first you need to have an account on Bitly.

As we are going to use Bitly API, we need to generate an access token that is mandatory to interact with the APIs. To generate the access token, go to your Edit Profile page. Click on the top-right settings menu and then select your username/email.

Your Account

On the next page, you will see the option for ‘Generic Access Token’. Click on it and copy your access token which we need in a moment.

Access Token

In order to create a short link with Bitly, it needs to send the HTTP POST request to the API endpoint. I am going to write a code for both Guzzle and cURL to send HTTP requests and receive HTTP responses.

Send HTTP Request Using Guzzle

For sending HTTP requests, we can use either Guzzle or cURL. But, I recommend using Guzzle as it does not require a cURL extension enabled on your server. Plus, Guzzle provides a clean code as compared to cURL.

Install the Guzzle library in your project using the command:

composer require guzzlehttp/guzzle

Upon package installation, write the below code in your PHP file which generates TinyURL for you.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'https://api-ssl.bitly.com/',
    ]);
     
    $response = $client->request('POST', 'v4/bitlinks', [
        'json' => [
            'long_url' => 'YOUR_LONG_URL',
        ],
        'headers' => [
            'Authorization' => 'Bearer YOUR_ACCESS_TOKEN'
        ],
        'verify' => false,
    ]);

    if(in_array($response->getStatusCode(), [200, 201])) {
        $body = $response->getBody();
        $arr_body = json_decode($body);
        echo $arr_body->link;
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

Make sure to replace the placeholders YOUR_LONG_URL and YOUR_ACCESS_TOKEN with the actual values. This code gives a call to the https://api-ssl.bitly.com/ with the endpoint v4/bitlinks. In response, you will get your short URL.

Send HTTP Request Using cURL

I am recommending Guzzle for HTTP requests. But still, if someone wants to use cURL then they can use the below code. Actually, a choice is up to the user. If you are using cURL already on your application then obviously you go for cURL. Both methods are giving the same result. So decide on any one method which is suitable for you.

<?php
$url = 'https://api-ssl.bitly.com/v4/bitlinks';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['long_url' => 'YOUR_LONG_URL']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer YOUR_ACCESS_TOKEN",
    "Content-Type: application/json"
]);
 
$arr_result = json_decode(curl_exec($ch));
echo $arr_result->link;

I hope you understand how to create TinyURL using Bitly API in PHP. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

4 thoughts on “Create TinyURL Using Bitly API in PHP

Leave a Reply

Your email address will not be published.