Location: PHPKode > scripts > untiny > untiny/untiny.php
<?php
/*
 * Author: James Hinds
 * The author makes no claims regarding copyrights.  Do with it what you will.
 *
 * Problem:  Where do those tinyurl's really point to?
 *
 * This class will follow the 'Location:' headers and return the last one
 * from the HTTP responses as they comes through.
 *
 * The body of the final HTML site is not accessed to avoid useless data transfers.
 *
 * For more info on CURLOPT_HEADERFUNCTION and CURLOPT_WRITEFUNCTION see:
 * <http://curl.haxx.se/libcurl/c/curl_setopt.html>
 * */
class untiny {
	var $location;
	var $errorMsg;

// requires libcurl  support for PHP (Rev level 7.7.2 or above)
function read_header($ch, $string)
{
	//libcurl must see the exact length of the untrimmed input string
	 $length = strlen($string);
	 // but we dont want any trailing \r \n or other stuff
	 $string=trim($string);
	 if( preg_match('/Location:(.*)/',$string,$dummy)) {
		 $this->location = trim($dummy[1]);
	 }
	 //echo "Header: $string\n";
	 return $length;
}

function resolveError () {
	return $this->errorMsg;
}

function untiny_url($url) {
	// pass in the url to resolve, we return the final destination or false
	$this->location = $url;
	$this->errorMsg = "";

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
	curl_setopt($ch, CURLOPT_NOBODY,1);

	 //Set callback function for headers
	 curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'read_header'));

	 curl_exec($ch);
	 $this->errorMsg = curl_error($ch);
	 // Do not re-use the curl channel
	 curl_close($ch);

	 return $this->errorMsg?false:$this->location;
 }

}

$test_me=true;
if ( $test_me ) {
	$resolve = new untiny();
	if ( $final = $resolve->untiny_url('http://tinyurl.com/cm6kcz')) {
		echo("Resolves to $final\n");
	}
	if ( $final = $resolve->untiny_url('http://romancecapitol.com/')) {
		echo("Resolves to $final\n");
	}
	if ( $final = $resolve->untiny_url('http://www.romancecapitol.com/')) {
		echo("Resolves to $final\n");
	}
}

?>
Return current item: untiny