0

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?

Zhihao
  • 14,758
  • 2
  • 26
  • 36
user3125898
  • 57
  • 1
  • 6

3 Answers3

3

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.

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291
  • 1
    No, not the shown part. I'm just saying it's not necessary anymore to manually take care about such things. – mario Dec 29 '13 at 06:14
2

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.';
    }
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0
  $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';
  }
chanchal118
  • 3,551
  • 2
  • 26
  • 52