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;
}
2 Answers 2
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.
1 Comment
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().Setting to UTF-8 encoding will solve your problem. I also used that script and that illegal characters isn't generated. generated-chars
uniqidonly returns 0-9a-f, but your point still stands; there's no reason to usecrypt.cryptusing? You can test using Example #3 in the PHP documentation.crypt()is outputting binary data. It's not intended to be processed using string handling functions. It won't ever contain any HTML tags, sostrip_tags()is utterly redundant. It hasn't been escaped usingaddslashes()so you shouldn't be usingstripslashes()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 callingcrypt()in the first place? Just useuniquid()on its own. Job done