Tiny url encode and decode with PHP

The first functions make short urls using tinyurl.com service. It’s a very popular function on the web, you can find it in a lot of files, and it’s always the same:

function doShortURL($url) {
	$short_url= file_get_contents('http://tinyurl.com/api-create.php?url=' . urlencode( $url ) );
	return $short_url;
}

The second function decode a short url in a simple way: I’ve used CURL to get the http header of the short url page. If the header contains a “Location:” header, then it’s a redirect, and the decoded url is the url in the “Location” header string, here is the code:

function doShortURLDecode($url) {
	$ch = @curl_init($url);
	@curl_setopt($ch, CURLOPT_HEADER, TRUE);
	@curl_setopt($ch, CURLOPT_NOBODY, TRUE);
	@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
	@curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$response = @curl_exec($ch);
	preg_match('/Location: (.*)\n/', $response, $a);
	if (!isset($a[1])) return $url;
	return $a[1];
}

These functions are included in the Mini Bots Class.

  1. PHP bot to get wikipedia definitions
  2. get MySpace events with a PHP function
  3. Test if a remote url exists with PHP and CURL
  4. PHP to get twitter infos and avatar
  5. PHP code to check if remote mp3 exists

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>