0

I have tried it standalone many many times and i got no ID with illegal character. Well, But when the code below working on my website, it is generating illegal characters like: XY�DV3VD, L6XÝOMJ3

The output must consist of [A-Z] and [0-9]. How this could be? Thanks for ideas.

function uniqeeID($len){

    //generate a random id encrypt it and store it in $rnd_id 
    $rnd_id = crypt(uniqid(rand(),1)); 

    //to remove any slashes that might have come 
    $rnd_id = strip_tags(stripslashes($rnd_id)); 

    //Removing any . or / and reversing the string 
    $rnd_id = str_replace(".","",$rnd_id); 
    $rnd_id = strrev(str_replace("/","",$rnd_id)); 

    //finally I take the first $len characters from the $rnd_id 
    $rnd_id = strtoupper(substr($rnd_id,0,$len));

    return $rnd_id;

}
  • 1
    why crypt it? uniqid already returns a-z0-9 data... – Marc B Aug 02 '13 at 15:33
  • @MarcB Actually, `uniqid` only returns 0-9a-f, but your point still stands; there's no reason to use `crypt`. – kba Aug 02 '13 at 15:37
  • In fact, it is not something really necessary. –  Aug 02 '13 at 15:39
  • What algorithm is `crypt` using? You can test using [Example #3 in the PHP documentation](http://php.net/crypt). – kba Aug 02 '13 at 15:42
  • 2
    `crypt()` is outputting binary data. It's not intended to be processed using string handling functions. It won't ever contain any HTML tags, so `strip_tags()` is utterly redundant. It hasn't been escaped using `addslashes()` so you shouldn't be using `stripslashes()` on it. All that makes it look like you don't really know what you're doing, but you want to make it look "secure". And the other string handling calls are equally pointless. But as others have said, if you want alphanumeric output, why are you calling `crypt()` in the first place? Just use `uniquid()` on its own. Job done – Spudley Aug 02 '13 at 15:50
  • I found this script from somewhere, this code will not be using on a banking system. Thanks for judgement. –  Aug 02 '13 at 16:06

2 Answers2

0

Technically it's not generating illegal characters, it's just generating characters that don't fit your character encoding settings.

Easiest way for you to bypass this without doing too much research is to construct a string of all the characters you want, it may sound like a overhead but it's a solid solution.

$allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

An excelent solution of how to finish the deal can be found here.

Community
  • 1
  • 1
Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • `array_rand()` returns an array of indices, so your function will just implode the those, resulting in a string of only numbers. Besides, using `array_rand()`, no character can appear more than once. And no, there's no reason for `shuffle()`. – kba Aug 02 '13 at 15:48
0

Setting to UTF-8 encoding will solve your problem. I also used that script and that illegal characters isn't generated. generated-chars

JMMaguigad
  • 29
  • 4