5 minute module

<< Go back | Posted: Saturday, December 13 2008 - 20:53

Tags: drupal, link, module

I wanted to create a quick module to track my links. I can give them a code (for example http://domain.com/linkybits/876563), where 876563 would lookup a link in the database, and then get redirected, plus update the hits counter.
Simple concept, has been done billions of times in the past. Probably a module out there somewhere to do it plus more, but what the hell :)

I created a MySQL table called linktrack, with ltid (INT 11 auto_increment), link (text) and hits (INT 11, NOT NULL, default 0).

For the sake of the link example here, I want to take out the 56719 segment of this link, and use that to check in the database to grab the proper link: linkybits/14/08/2008/56719/this_is_a_test_title

Take into account that this may need more sanitization, and proper error messages etc. You should get the idea:


/**
 * Implementation of hook_menu.
 */
function whatever_menu($may_cache) {
	$items = array();
	if (!$may_cache) {
		$items[] = array(
			'path' => 'linkybits',
			'title' => t('Link Track'),
			'description' => t('xxx'),
			'callback' => 'linkybits',
			'type' => 'menu_callback',
			'access' => user_access('access content')
		);
	}
	return $items;
}


function linkybits() {
	$number_of_args = func_num_args();
	if ($number_of_args >= 4) {
		$theID = func_get_arg(3);
		$query = "
			SELECT l.link FROM {linktrack} l WHERE l.ltid = %d 
		";
		$result = db_result(db_query($query, $theID));
		
		if ($result) {
			$query = "
				UPDATE {linktrack} l SET l.hits = l.hits + 1 WHERE l.ltid = %d 
			";
			db_query($query, $theID);
		}
		else {
			return t('There is no infomation associated with that link.');
		}
		
		if (preg_match('/^http/i', $result)) {
			drupal_goto($result);
		}
		else {			 
			return t('If you see this page, then the link you have clicked on hasn\'t worked. The administrator will be informed of this error. Sorry for the inconvenience.');
		}
	}
        else {
		return t('The link you clicked on is invalid.');
	}
		
}

You can also expand this, to store extra information in the database. Of course, if we are adding the links manually to the link table, then we should create a page in administration to handle that also.

Most people these days go for more fancy alternatives, like analytics and other services to see exactly what their site is doing. This is still good fun to play about with though :)


click here to add a comment