Generate a TinyURL with PHP

TinyURL allows you to take a long URL like "http://www.developer-paradize.blogspot.com" and turn it into "http://tinyurl.com/n48rbym". Using the PHP and TinyURL API, you can create these tiny URLs on the fly!. Simply provide the URL and you'll received the new, tiny URL in return.

PHP
<?php
//gets the data from a URL
function get_tiny_url($url)  {
$ch = curl_init();
$timeout = 5; 
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//test it out!
$new_url = get_tiny_url('http://www.developer-paradize.blogspot.com/');

//returns http://tinyurl.com/n48rbym
echo $new_url;
?>
If you don't want to use cURL, you can use file_get_contents.
PHP
<?php
function tinyurl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
}
//test it out!
$url = tinyurl('http://www.developer-paradize.blogspot.com/');
//returns http://tinyurl.com/n48rbym
echo $url;
?>

Note: If the server has disabled the file_get_contents() it will create unwanted problem. So I strongly recommend to use cURL() and it will work fine.

Comments

Post a Comment

Popular Posts