Today’s anonymous submission starts with “I inherited an old wordpress site that uses an external corporate authentication server for logins.”

As one might expect, the result is a hodgepodge of reinvented wheels and anti-patterns. Deep in the authentication code, there’s a method to add an email subscription. You might ask yourself, “What does adding an email subscription have to do with authentication?” and you’ve already put more thought into the design than the original developer.

In any case, you want to assign each subscription a unique identifier. You’re not planning to use this as a key, you’ve just decided it’d be nice to have, I suppose. So what is the best way to generate a unique ID? Well, as a hint, the variable that holds the unique ID is called $guid, so obviously, we’re going to… do this:

function add_subscription_user($user_id, $user_name, $user_email, $group) {
	$guid = rand();
	$length = 6;
	global $wpdb;
	$db_prefix = $wpdb->prefix;
	
	//$rand1 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$rand2 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$rand3 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$rand4 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$rand5 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$rand6 = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
	$guid = $user_id."-".$rand2."-".$rand3."-".$rand4."-".$rand5."-".$rand6;
	$CurrentDate = date('Y-m-d G:i:s');
	
	$sql = $wpdb->prepare("INSERT INTO `".$db_prefix."es_emaillist` 
			(`es_email_name`,`es_email_mail`, `es_email_status`, `es_email_created`, `es_email_viewcount`, `es_email_group`, `es_email_guid`)
			VALUES(%s, %s, %s, %s, %d, %s, %s)", array($user_name, $user_email, 
			'Confirmed', $CurrentDate, 0, $group, $guid));
	$wpdb->query($sql);
	//return $wpdb->insert_id;
}

That’s not a GUID or a UUID. That’s random nonsense. Take every letter in the alphabet, shuffle it, and then grab the first six characters. Repeat that five times. Slap the user’s ID on the front, and call that a GUID, or es_email_guid, if you’re speaking database.

Our submitter adds:

Sadly, this is one of the better snippets of code I’ve found. The plan now is to recommend we nuke this from orbit and start over with either a fresh Wordpress installation or a totally different platform.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!