Short URL using Bitly and PHP

Many services like Twitter and others uses Short URL for sharing links. It helps reduce the size and complexity of a long URL. The major benefit of short URL is that they are small and very easy to remember.

There are many URL Shorteners available. The Bitly.com is one of popular service provider for shortening the URLs.

In this article, we will learn to use Bitly.com API with PHP. For this, we will use a client library Bitly PHP Client. This library provides various wrapper functions to access the Bitly APIs.

Prerequisites

To use Bitly API, first you need to create an account at Bitly.com and get your access token from here.

Your PHP version should be greater than 5.6

Setup

You can install the library using Composer.

We are now ready to go!

Usage and examples

Simply, load the library using composer autoload option and include the namespace in the beginning of your PHP file. See below example.

Now, to access the APIs, create an object of BitlyClient class and pass your token in constructor function like,

That is it.

Short URL

To short an URL, use the shorten() method. This method returns a Bitlink (short url) for a given link. See below example,

For all available functions and methods, please refer to its documentation.

Response format

This library provides the support of json, xml and txt formats. The default format is json.

You can pass the response format in options array like below,

Enjoy!

You may also like...