Random Code Generator

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ScottCFR
Forum Commoner
Posts: 33
Joined: Sat Jun 19, 2010 7:36 pm

Random Code Generator

Post by ScottCFR »

Hey all,

I am learning PHP and I can't find any tutorials or anything for this matter. I am designing a referral system and I want it so after someone registers it emails them the unique code like mydomain.com/referalid?=647364 or something. I know a bit of PHP but this gets to me.

Thanks,
Scott W.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Random Code Generator

Post by requinix »

What if you gave sequential codes to each person? First person gets 1, second gets 2, and so on. You can start the numbering anywhere you want: first person gets 294398, second person gets 294399, third gets 294400, etc.
If you want letters too you can do base conversion: 294398 in decimal is 47dfe, for instance.

But that's not actually random: if a person signed up twice they'd see a pattern (albeit a pattern visible everywhere else on the Internet). Does it have to be actually random? Creating unique, "truly" random identifiers can be tricky.
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Re: Random Code Generator

Post by JKM »

Something like this?

Code: Select all

function makeCode($length) {
	$code = '';
	$poss = "ABCDEFGHIJKLMOPQRSTUVWXYZ0123456789abcdefghijklmopqrstuvwxyz";
	$i = 0;
	while($i < $length) {
		$char = substr($poss, mt_rand(0, strlen($poss)-1), 1);
		if(!strstr($code, $char)) {
			$code .= $char;
			$i++;
		}
	}
	return $code;
}
Example:
makeCode(10);
ScottCFR
Forum Commoner
Posts: 33
Joined: Sat Jun 19, 2010 7:36 pm

Re: Random Code Generator

Post by ScottCFR »

Well, What I am trying to do is make it so that it says "Blank refered you" so it detects who the owner of that ID is.

And that code. It will be different every time?

Thanks,
Scott W.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Random Code Generator

Post by Apollo »

Code: Select all

$id = sha1(time().uniqid(mt_rand(),true));
This will give you a unique, non-guessable ID, consisting of hexadecimal chars only (i.e. 0-9 and a-f).
Post Reply