Skip to content

Instantly share code, notes, and snippets.

@wouterds
Created May 27, 2013 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wouterds/5657286 to your computer and use it in GitHub Desktop.
Save wouterds/5657286 to your computer and use it in GitHub Desktop.
So I'm finally going to rewrite my url shortener.. But I have some performance issues.. This is de function I use to generator a random code (short url) for a long url. This works fine. For now.. Each time when someone generates a code this is checked with the database if it doesn't exist yet, if it does, this process starts all over again until…
<?php
/**
* @author: WouterDS
* @created: 01/01/13, 22:28
* @filename: CodeGenerator.php
*/
class CodeGenerator {
public static function randomCode($length = 4, $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
$converted = '';
$codesetLength = strlen($codeset);
for($i = 0; $i < $length; $i++) {
$randomCharacter = substr($codeset, floor(rand(0, $codesetLength)), 1);
$converted .= $randomCharacter;
}
return $converted;
}
}
@tvbeek
Copy link

tvbeek commented May 27, 2013

You can "create" 62 positional numbering system (like hexadecimal is 16)
Then you can convert a auto increment value to the short value (and back)

It's not fully random but if you use the characters in a random order it can be pseudo random

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment