tinyURL

A recent project I was working on required that I create dynamic urls, and rather than using the full www.example.com/some-file?id=some-numbers I wanted to create a short url.

Using the super simple tinyurl.com api I was able to quickly create the urls. I created a php class that will help you quickly create and deploy short urls!

To use the tinyURL class just pass it your desired URL and it will take care of the rest!

the code:

// include tinyURL
include('class.tinyURL.php');

// create new object
$tiny = new tinyURL();

// pass tinyURL the desired url
$newU = $tiny->shorten('http://drewdahlman.com');

// echo it out!
echo $newU;

 

class.tinyURL.php

// TINY URLS
// AUTHOR: DREW DAHLMAN
// DATE: 11.7.2011
// VERSION: 1.0
// NOTES:
// To use this class simply include in your php document. include('class.tinyURL.php');
// To create the url $tinyURL->shorten($url);
// The class will create the url and return it for your use!

class tinyURL{
    function tinyURL(){
        
    }
    public function shorten($u){
        // Tiny URL API CALL
        $daurl = 'http://tinyurl.com/api-create.php?url='.$u;
        
        // GET THE CONTENT
        $handle = fopen($daurl, "r");

        // If there is something, read and return
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 4096);
                return $buffer;
            }
            fclose($handle);
        }
    }
}

 

In the zip you'll find an index.php and the class you can see how they work there!

DOWNLOAD

comments