I have this code and would like to restrict the characters to [a-f][A-F][0-9]
$code = mysql_real_escape_string($_POST['dgt']);
$len = strlen($code);
if (!($len == "32" or $len == "40")) {
print "This is not a valid code.";
} else {
echo 'success';
}
right now it has a character LENGTH limit and would like to add characters restriction as stated above.
what's the best possible way to achieve this?
Why don't you make use of a simple regex ?
if(preg_match('/[^a-f_\-0-9]/i', $code)) //if this regex doesn't work , make use of /[^a-fA-F0-9]/
{
if(strlen($code)==32 || strlen($code)==40)
{
echo "This is not a valid code.";
}
}
else
{
echo 'Success.';
}
$code = mysql_real_escape_string($_POST['dgt']);
$len = strlen($code);
if (!($len == "32" or $len == "40") or preg_match('/[^a-fA-F0-9]+/i', $code)){
print "This is not a valid code.";
} else {
echo 'success';
}
One could even accomplish the character and length assertion in a single regex:
if (preg_match('/^([[:xdigit:]]{8}){4,5}$/i')) {
// valid
}
That will match 4*8 (=32) or 5*8 (=40) hexdigits.
Btw, you're supposed to apply mysql_real_escape_string
last, or right before interpolating it into SQL strings. It makes little difference here, in particular as the values are asserted already. But modifying strings after SQL-escaping them might in some circumstances undo the escaping. You might wish to read up on parameterized queries anyway. That would have made that note redundant.