1

My regex looks like this.

    if (preg_match("/^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$/", $text) == FALSE) {
      echo 'Wrong!'
    }

I want to allow special characters ' and " sign too. How should I better implement it? And whether it is a security break for mysql database.

user3284181
  • 17
  • 1
  • 5

2 Answers2

1

SQL injection is best prevented by escaping anything that comes from the user. Without such,

WHERE x = '$x'

with $x being

' OR true OR '

turns into

WHERE x = '' OR true OR ''

thereby letting the hacker in without knowing the right value for x. Variants of this hack allow really nasty things to happen.

Escaping would give

WHERE x = '\' OR true OR \''

which will suitably fail, and the hacker will move on to another way to break through your defenses.

Rick James
  • 135,179
  • 13
  • 127
  • 222
0

Tell me exactly what characters and symbols you want to enable in the field? I will edit the regex.. Basically it should look like this:

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good!
}
else {
    #your string is wrong.
}
Ilanus
  • 6,690
  • 5
  • 13
  • 37