How to create a Custom short URL using PHP?

Hello Everyone,

If you are looking for a solution to create the sort url of any long url then you are on right place.

There are many website are avialable on goolge to create a short url, but tinyurl.com and bityl.com are most popular website to create a online short url. By these two website you can create your website short url and can share it with your friend or on social websites.

If you are looking to create custom short url then I am here going to explain how we can create a custom short url using tinyurl API.

If you have a wordpress website then you should need to add given below code into theme function.php file and if you have a core PHP website then you should need to add this function in your lib files.


<?php
function wpexperts_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;  
}
?>

Now point is how I can use this function to create the short url?

To use this is wpexperts_tiny_url() function you should not do much more, just pass the long url to this function and it will return a shortener URL just like magic :)

Example

<?php
$longurl = 'http://www.wp-experts.in/?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa&sourceid=chrome&ie=UTF-8';
$new_url = wpexperts_tiny_url($longurl);

echo $new_url;
?>

It will return daynamic short url as given below format

https://tinyurl.com/tyt2b2c

For wordpress site it will return the long url like http://www.wp-experts.in/blog/category/wordpress/ to short url https://tinyurl.com/tzgry9z
you should required only to pass the url into function


<?php
$short_url = wpexperts_tiny_url(get_the_permalink()); // to get dynamic current page url
$short_url = wpexperts_tiny_url('http://www.wp-experts.in/blog/category/wordpress/'); 
echo $short_url;
?>

To do this you have not requried any technical knowldge, just copy and paste the code and enjoy it.

Enjoy code!

Leave a Reply

Your email address will not be published. Required fields are marked *