Skip to content

Instantly share code, notes, and snippets.

@flesch
Created August 3, 2010 17:38
Show Gist options
  • Save flesch/506790 to your computer and use it in GitHub Desktop.
Save flesch/506790 to your computer and use it in GitHub Desktop.
Token
function guid() {
function hex(len) {
var s = '', n = len || 4;
while (s.length < n) {
s += (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return s.substr(0, n);
}
return [hex(8), hex(4), hex(4), hex(4), hex(12)].join('-');
}
function token(n){
var salt = 'abcdefghijklmnopqrstuvwxyz0123456789', key = '', len = n || 6, length = salt.length, i = 0;
if (length < len) {
while(salt.length < len) {
salt += salt;
}
length = salt.length;
}
for (; i<len; key+=salt.charAt(Math.floor(Math.random()*length)), i++);
return key;
}
<?php
function token($len = 6) {
$salt = 'abcdefghijklmnopqrstuvwxyz0123456789';
if (strlen($salt) < $len) {
while (strlen($salt) < $len) {
$salt .= $salt;
}
}
return substr(str_shuffle($salt), 0, $len);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment