Create Short URLs with PHP: shorten_url PHP Function

May 18th, 2010

Create Short URLs with PHP

Do you want to create short urls from within your own PHP application? Most url shortening services provide an API, it’s how apps like twitter clients provide built-in url shortening. I wrote a small PHP function to provide url shortening from two of the most popular services, is.gd and tinyurl.com. Where’s bit.ly I hear you ask. Well yeah, sure, that’s what all the cool kids are using these days, but bit.ly requires an API key. That’s not a huge issue, it’s free. It just doesn’t sit well with creating a nice portable, drop in a go PHP function. So bit.ly didn’t get an invite to my super mega PHP function party.

If you want to get some bit.ly action on the go then feel free to modify the code below accordingly. I might update this at some point. I keep thinking I should, but meh.

function shorten_url($url,$service='tinyurl.com') {

	// create the request url based on the selected shortening service
	switch ($service) {
	    case 'tinyurl.com':
	       $service_url = 'http://tinyurl.com/api-create.php?url='.urlencode($url);
		   break;
	    case 'is.gd':
	        $service_url = 'http://is.gd/api.php?longurl='.urlencode($url);
	}

	/*
	 * use cURL to fetch the respons
	 * Feel free to swap this out for
	 * $output = file_get_contents($service_url)
	 * if you have fopen wrappers enabled
	 */
	$ch = curl_init($service_url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch);

	// return false on error
	return strtolower(substr($output,0,5))=='error' ? false : $output;

}

The function defaults to tinyurl. Yeah. Interesting choice you’re thinking, but I’m old school and that’s how I roll. I’ve used curl to make the HTTP requests for the simple fact that when it comes to hosting curl support is enabled more ofthen than fopen wrappers is on (and you need fopen wrappers on to be able to do a file_get_contents on an url). Either way the result is the same. Use whichever method you like.

Expanding Short URLs With PHP

For expanding short urls on the fly with PHP see: PHP expand_url function

Posted in Web | Tagged with: ,

Only One Response

  1. How To Make Money With eBay

    Hurrah! At last I got a blog from where I can really
    take valuable data concerning my study and knowledge.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.