Maxim Chernyak posted an article on his blog about creating an authentication token using PHP. I wouldn’t recommend using this method to do that though. Even if the pattern looks quite complex, a computer will figure out the pattern using a hand full of valid keys. It’s very difficult to come up with an algorithm which is difficult to hack.

If you can keep information from the user, which Maxims article assumes as well, you can use MD5 to generate keys. Simply add a string you keep secret to each key.

define('SECRET', "s3cr3t"); # don't actually use this value
 
function make_token() {
  $str = "";
  for ($i=0; $i<8; $i++) $str = rand_alphanumeric();
  return $str . md5($str . SECRET);
}

If you want a shorter key (16 chars), you may use:

define('SECRET', "s3cr3t"); # don't actually use this value
 
function make_token() {
  $str = "";
  for ($i=0; $i<7; $i++) $str .= rand_alphanumeric();
  $pos = rand(0, 24);
  $str .= chr(65 + $pos);
  return $str . substr(md5($str . SECRET), $pos, 8);
}

Do note that a shorter key is less secure.

To validate you would do:

  function validate_token($str) {
    $rs = substr($str, 0, 8);
    return $str == $rs . substr(md5($rs . SECRET), ord($str[7])-65, 8);
  }

This code is not tested and may contain bugs